I am not sure if there is a mistake in my existing code or the functionality in Jquery Array is like below:
var categories = [];
$(this).children('categories').each(function() {
categories.push($(this).find('name').text());
});
Now when I have the below XML node :
<categories>
<name>a</name>
<name>b</name>
<name>c</name>
</categories>
I see that in Firebug the categories array has one element - "abc" but actually it should be as index 2 with values as 'a','b' and 'c'
Is there something wrong in my code?
Colin Brock
21.6k9 gold badges51 silver badges62 bronze badges
asked Mar 20, 2012 at 0:18
Programmer
8,84924 gold badges95 silver badges182 bronze badges
2 Answers 2
$(this).children('categories').each(function() {
$(this).find('name').each(function(){
categories.push($(this).text());
});
});
answered Mar 20, 2012 at 0:24
Frenchi In LA
3,1694 gold badges27 silver badges42 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
var categories = [];
$(this).find('categories name').each(function() {
categories.push($(this).text());
});
You are looping through each categories element (there is only one) and getting the text of all elements within it named name. Only one call to text means only one value. You need to loop over the names not the categories elements.
answered Mar 20, 2012 at 0:23
James Montagne
78.9k14 gold badges115 silver badges132 bronze badges
4 Comments
Phil
Actually, calling
.text() on a jQuery object containing multiple elements will concatenate the valuesJames Montagne
Right, into one single value. That's why there's only one value in the array.
Programmer
No I cannot use
find('categories name') cause I don't want all of it in the tree node (categories node is repetative down in XML tree). So I have to use .children onlyJames Montagne
So then use
children('categories').find('name') don't use two each loops like the answer you picked.lang-js