Question

There are some preferences I have observed for the selection syntax such as:

 $('#mydiv > a.selectMe').hide();
 $('#mydiv').children('a.selectMe').hide();

To me, it seems a bit confusing as the documentation for jQuery is a bit ambiguous here:

" parent > child Returns: Array Matches all child elements specified by "child" of elements specified by "parent". "

and

" children( expr ) Returns: jQuery Get a set of elements containing all of the unique immediate children of each of the matched set of elements. "

The question that needs to be clarified in MY mind is whether the first form returns ALL children/grandchildren or just the immediate children as the second form indicates is true. One of these is the "selector" form and the other under "traversing" on the jQuery documentation pages, which to me are similar functional tasks but not exactly the same thing.

SO, the questions here are:
Which form is faster? Do they REALLY select the same thing, or does the 'parent > child' form select grand children as well as immediate children?

Was it helpful?

Solution

$('#mydiv a.selectMe') - Finds all anchors with the class 'selectMe' that are decendents of the tag with ID "mydiv". These could be nested deeply.

$('#mydiv > a.selectMe') - Finds immediate children.

As for which is faster between your two examples of getting immediate children... I did some time trials to test.

I had a page with 10,000 anchor tags with the class 'selectMe', within a Div with ID 'mydiv'.

$("#mydiv").children("a.selectMe") - 485ms
$("#mydiv > a.selectMe") - 374ms

Basically, it's a negligible difference though doing everything using selectors was consistently faster. If you have 10k anchors on a page, you're facing an entirely different problem, though. :-)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top