jQuery selector combination to get to my element - javascript

Okay so looking at the image, the highlighted section is the element i need to get too. I need to store the data-id value which is 2391 in the example above.
So starting from the anchor tag with the data-id value of "2392", how do i achieve this.
This is what i have done with no joy.
// This is finding the element, currentID is 2392.
var currentReview = $('.modelLink[data-id="'+ currentID +'"]');
var nextID = currentReview.closest('tr').next().children('td').next().next().next().children('.modalLink').data('id');
How can i achieve this?

Try
var currentReview = $('.modelLink[data-id='+ currentID +']');
var nextID = currentReview.closest('tr').next().find('td a.modalLink').data('id');

Instead of trying to traverse from one deeply-nested anchor to another, just grab all of the IDs into an array and traverse the array--much easier!
// Put all anchor IDs into an array
var ids = [];
$.each("a.modelLink", function( index, value ) {
ids.push(value.attr("data-id"));
});
// Creates: ids[0] = 2391, ids[1] = 2392, etc.
After that, you'll be able to traverse the anchors without worrying about DOM traversal.
// This is finding the element, currentID is 2392.
var currentID = 2392;
var currentReview = $('.modelLink[data-id="'+ currentID +'"]');
// Ensure we do not go out of bounds
current_index = ids.indexOf(currentID);
if(current_index >= 0 && current_index < ids.length - 1) {
nextID = ids[current_index + 1];
}
else {
// Start over from the beginning
nextID = ids[0];
}
// Easily assign the nextReview
nextReview = $('.modelLink[data-id="'+ nextID +'"]');

Related

search for element within element by tagname

After being stuck for a few hours on this problem, i think it is time for call for help on this.
Situation
I have a XML file which i need to filter and group. I've managed to filter it with the :Contains part. I've also determined the nodes on which i need to group (the getGroups function gives those back to me). Now i want to create a new XML with the filtered values and grouped by the returned keys.
Code
var XMLElement = document.createElement("DataElementsCalc");
jQuery(xml).find("DataElements " + topNodes + filter).each( function() {
var dataSetTemp = this.parentNode;
if(calculation1 != "")
{
var groupKeys = getGroups(dataSetTemp,calculation1);
var tempXML = XMLElement;
jQuery(groupKeys).each(function (key,value) {
var tempValue = 'a' + value.toLowerCase().replace(/\W/g, '');
if(tempXML.getElementsByTagName(tempValue).length > 0)
{
tempXML = tempXML.getElementsByTagName(tempValue);
}
else
{
var Node = document.createElement(tempValue);
tempXML.appendChild(Node);
tempXML = Node;
}
});
var Node = document.createElement("InfoSet");
var x = dataSetTemp.childNodes;
for (i=0; i < x.length; i++)
{
if(x[i].nodeType == 1)
{
var tempElement = document.createElement(x[i].nodeName);
tempElement.innerHTML = x[i].childNodes[0].nodeValue;
Node.appendChild(tempElement);
}
}
tempXML.appendChild(Node);
}
});
Explanation
As said in the situation, i already filtered the XML and have the groupNames from the getGroups function. There are a few other things i need to explain for this code:
tempValue is being build as a a + value.toLowerCase().replace(/\W/g, '');. This is being done because i possible get dates into the groupKeys. This way the node name is getting a working name (i received errors on other ways).
I want to create a new XML which is leveled by the groups. If a group already exists, i want to create a new element in it, not get a new group with the same name. (my problem at the moment).
Problem
As mentioned above, the groups aren't checked properly. Firstly: tempXML.getElementsByTagName(tempValue).length returns the error that the function tempXML.getElementsByTagName does not exists. Secondly: If i change this to document.getElemetsByTagName I get a lot of the same nodes in my XML file.
Effect
The grouping effect doesn't work as it should. I get OR an error, OR a lot of the same nodes in my DataElementsCalc.
Questions
How can i solve this? How do create nodes beneath specific nodes (for if there is a group A beneath group 1 as well as beneath group 2)?
Tried
Change tempXML to document on different places (all getElementsByTagName, at the same time or not). Looked for another way to create a XML which is easier to handle (haven't found one, yet)
As mentioned by myself in the comments of the question:
I also don't see anything in the source code for this (maybe this is the reason why it doesn't work??)
I tried to place the XMLElement into an existing element on my webpage (like this:
var XMLElement = document.createElement("DataElementsCalc");
jQuery('.basicData').append(XMLElement);
in which basicData is a class of an existing element).
Now i do get a list of all elements ordered on the groups i wanted.
Final version
var XMLElement = jQuery("<DataElementsCalc/>");
jQuery('.basicData').append(XMLElement);
jQuery(xml).find("DataElements " + topNodes + filter).each( function()
{
aantalElementsTotal++;
var dataSetTemp = this.parentNode;
if(calculation1 != "")
{
var groupKeys = getGroups(dataSetTemp,calculation1);
var tempXML = XMLElement;
var groupId = '';
jQuery(groupKeys).each(function (key,value) {
var tempValue = 'a' + value.toLowerCase().replace(/\W/g, '');
groupId += 'a' + value.toLowerCase().replace(/\W/g, '');
if(jQuery("#" + groupId).length > 0)
{
tempXML = jQuery("#" + groupId);
}
else
{
var Node = jQuery("<"+tempValue+"/>");
jQuery(Node).attr('id', groupId);
jQuery(tempXML).append(Node);
tempXML = Node;
}
});
var Node = jQuery("<InfoSet/>");
var x = dataSetTemp.childNodes;
for (i=0; i < x.length; i++)
{
if(x[i].nodeType == 1)
{
var tempElement = jQuery("<"+x[i].nodeName+"/>");
jQuery(tempElement).text(x[i].childNodes[0].nodeValue);
jQuery(Node).append(tempElement);
}
}
jQuery(tempXML).append(Node);
}
});

How to find & retrieve a node position without relying on id, class or content in javascript

Context:
I need to keep the node selection of an user & be able to retrieve it later.
If there is an id on the html node I will use it.
But the problem arrive when there is no ID. I need to be able to mark this node & be able to find it back even after a page refresh.
I tried a couple of things with childnodes but I failed so far.
You can use the nodes position relative to its siblings to locate it within the dom. When dealing with nested elements, you simply prefix the nodes location with its parents location relative to its siblings. So you end up with a node identifier looking something like this: 2/0/4/1 Where each / corresponds to an additional level of depth. Here is a working example:
function getNodePosition(node){
var node = $(node);
var result;
var parent = node.parent();
var siblings = parent.children();
var pos = siblings.index(node);
result = '/' + pos;
if(parent.length && !parent.is('body')){
result = getNodePosition(parent) + result;
}
return result;
}
function getNodeByPosition(position){
var node = $('body');
var layers = position.substring(1).split('/');
$.each(layers, function(index, val){
val = parseInt(++val);
node = node.find(':nth-child(' + val +')')
});
return node[0];
}
Jsfiddle

DOM element not being found after cloning and appending unique ID

So I'm creating a random string value:
var randomString = function(stringLength) {
var i = 0;
stringLength = stringLength || 10;
var chars = '0123456789ABCDEFGHIJKLMNOPQRSTUVWXTZabcdefghiklmnopqrstuvwxyz';
var randomString = '';
for (i = 0; i < stringLength; i += 1) {
var rNum = Math.floor(Math.random() * chars.length);
randomString += chars.substring(rNum, rNum + 1);
}
return randomString;
};
And associating it with a list element on one pane:
var addUniqueId = function($thumbnail) {
var random = randomString(10);
$thumbnail.attr('id', 'rand-' + random);
};
And then cloning it and moving that list element to the right:
var cloneImage = function($thumbnail) {
addUniqueId($thumbnail);
var $lastImgAdded = $('.js-gallery-edit-pane li').last();
var span = $('<span />');
span.addClass('x').text('x');
var $clone = $thumbnail.clone(true, true).appendTo($('.js-gallery-edit-pane')).prepend(span).hide().fadeIn(200).unbind('click');
bindRemoveHandler($clone);
};
Then I add an overlay to the list element on the left to "gray" it out. Everything works at this point.
From there, a user can remove the recently cloned items on the right hand side by clicking the "X" on the image. This works fine and removes that recently cloned image, however, the original overlay is not being found. It should be associated with the random string value, so I'm just looking for that in $('.js-gallery-select-pane').find('#rand-' + string).find('.overlay').remove(); but for some reason it's not finding it...
Any idea why?
JSFiddle Demo
If you put an alert(string) in your code, you will see that the string already includes rand- so in your selector just do:
$('.js-gallery-select-pane').find('#' + string).find('.overlay').remove();
Here is the working JSFiddle
You have two collections of elements with ID pairs in them.
There's three problems though. The first two problems problem are here..
You were taking the complete id of the clone 'rand-etctcetc'
then adding rand- to it again 'rand-rand-etcetcetc' then using it as a selector. $('rand-rand-etcetcetc'). Instead I changed it to just add the neccessary # to the id. You also need to remove the js-gallery-editing class in order to let you add things back to the list on right hand side.
var bindRemoveHandler = function($thumbnail) {
$thumbnail.on('click', function() {
$(this).fadeOut(200, function() {
var string = $(this).attr('id');
$('.js-gallery-select-pane').find('#' + string).removeClass('js-gallery-editing').find('.overlay').remove();
$(this).remove();
updatePictureCount();
});
});
};
You could stop here but, you also have a different problem. The ID attribute is intended to be unique. Try using a custom attribute and the Jquery attribute equals selector. The query you want would look something like this..
$('.js-gallery-select-pane').find('[pairid="' + string +'"]');
Here, have a fiddle: http://jsfiddle.net/s3dCB/

Get list elements and its classes using jquery

I used $('#ul li').get() to get all the list elements and stored in an array, each of this list elements have classes...
var i;
var listClass = ('#ul li').get();
for(i=0;i<listClass.length;i++){
var theClass = listClass[i].attr("class"); //<--what's the proper function/method/code for this?
var content = listClass[i].innerHTML; //<-- works very well
//other codes here
}
How may i able to get the classes of each list elements...Thanks!
You can use jQuery's own map to do that:
alert($('#ul li').map(function() {
return this.className;
}).get());
http://jsfiddle.net/MhVU7/
for example. You can do anything with the returned array.
The reason the way you're doing it isn't working is because you're calling the non-existent method .attr on a native DOM element - it's not an extended jQuery object.
var lis = document.getElementById("ul").children;
for (var i = 0, len = lis.length; i < len; i++) {
var li = lis[i],
className = li.className,
value = li.value,
text = li.textContent;
// code
}
The get() method returns a native array of DOM elements, not a jQuery object.
You should use jQuery:
var lists = $('ul li');
var className = lists.eq(i).attr('class');
var content = lists.eq(i).text();
If you want to loop through all the elements
$('ul li').each(function(){
var className = $(this).attr('class');
var content = $(this).text();
});
I have commented the code to better help you understand it.
$("#ul li").each(function() { /* you should only be using # selector to identify id's - if it's all ul's you want just put ul. */
var klass = this.className; /* this refers to the native DOM object, which contains className */
var textContents = this.innerText || this.textContent; /* the text of the list, does not include html tags */
var childNodes = this.childNodes; /* the child nodes of the list, each unencased string of text will be converted into a TextNode */
console.log(klass + ' ' + textContents); /* replace console.log with alert if you do not have a console */
console.log(childNodes);
});
here is an example of the above.
Good Luck!

Get array of ids from e.g xx_numbers

How can I retrieve an array of ids with only a prefix in common?
E.g.
I've got a list of say 50 divs and they all got and ID looking like: aa_0000. Where 'a' is a prefix and '0' represents random numbers.
You want all elements of which their id starts with something common?
Assuming they are all div elements, this should work....
// Just so we can stay DRY :)
var prefix = 'aa_',
matchElement = 'div';
// Do we have an awesome browser?
if ('querySelectorAll' in document) {
var matchedDivs = document.querySelectorAll(matchElement + '[id^="' + prefix + '"]');
} else {
var allDivs = document.getElementsByTagName(matchElement),
matchedDivs = [],
regex = new RegExp('^' + prefix);
for (var i = 0, allDivsLength = allDivs.length; i < allDivsLength; i++) {
var element = allDivs[i];
if (element.id.match(regex)) {
matchedDivs.push(element);
}
}
}
console.log(matchedDivs.length); // Expect 3
jsFiddle.
If you want to explicitly match ones with numbers, try the regex /^aa_\d+$/.
If you have jQuery floating around, you can use $('div[id^="aa__"]').
For people using jQuery:
$('div[id^="aa_"]')

Categories

Resources