3

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?

2 Answers 2

7
$(this).children('categories').each(function() {
    $(this).find('name').each(function(){
        categories.push($(this).text());
    });
});
Sign up to request clarification or add additional context in comments.

Comments

3
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.

4 Comments

Actually, calling .text() on a jQuery object containing multiple elements will concatenate the values
Right, into one single value. That's why there's only one value in the array.
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 only
So then use children('categories').find('name') don't use two each loops like the answer you picked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.