R Clowes
R Clowes

Reputation: 69

Jquery ChildElementCount

Sorry for the jquery ajax xml 101 question ...

I have 2 questions: 1) Counting the child nodes inside the <RESULTS>. In this case there's only element happens to be called OBS. I want to know the jquery method for doing this. I have it with long hand javascript. 2) Can you advise the preferred method for accessing these counts (read down).

XML file looks like this...

<TABLE>
 <RESULTS>
  <OBS>..</OBS>
 </RESULTS>
 <RESULTS>
  <OBS>..</OBS>
 </RESULTS>
</TABLE>

There are 2 <RESULTS> and 1 child <OBS> returned. I've got that covered with ...

Long hand Javascript:

var items = request.responseXML.getElementsByTagName('RESULTS');
console.log("child Element Count= ",items[0].childElementCount); // will return 1 = OBS
console.log("nodes Count= ",items.length); // will return 2 =RESULTS

So we're good with that but with jquery.

Short hand Jquery:

var count=$(result).find("RESULTS").size();         
var countLength=$(result).find("RESULTS").length; 

Both will return "2". How do I get to the count of the child elements? In this case the answer would be 1 as there's just <OBS>

Thanks in advance.

Upvotes: 5

Views: 8004

Answers (3)

rodude123
rodude123

Reputation: 300

Why not try this instead

$("RESULTS:first-child").children().length

Upvotes: 2

Brad Christie
Brad Christie

Reputation: 101604

I'm not entirely sure what you're asking, but I'll show a couple of examples that may get you going:

// original XML string
var xml = '<TABLE><RESULTS><OBS>..</OBS></RESULTS><RESULTS><OBS>..</OBS></RESULTS></TABLE>';
// XMl -> jQuery object
var $xml = $($.parseXML(xml));

// Total item counts
var numberOfResults = $xml.find('RESULTS').size();
    console.log(numberOfResults); // output: 2
var numberOfObs = $xml.find('RESULTS>OBS').size();
    console.log(numberOfObs); // output: 2

// item count specific to the first <RESULTS> node:
var $firstResultsNode = $xml.find('RESULTS').first();
var numberOfObs = $firstResultsNode.children('OBS').size();
    console.log(numberOfObs); // output: 1

Upvotes: 0

Blender
Blender

Reputation: 298146

$(result).find("RESULTS").length counts the number of <RESULTS> elements. You're looking for the number of child elements in the first <RESULTS> element:

var count = $(result).find('RESULTS').first().children().length;

Upvotes: 5

Related Questions