The way the browser works is that upon load it creates an in-memory DOM tree which looks as follows:
P
_______________|______________
| |
childNodes attributes
______________|___________ |
| | | title = 'Test paragraph'
'Sample of text ' DIV 'in your document'
|
childNodes
__________|_______
| | |
'HTML you might' B 'have'
So when you lookup P > DIV > B
, the lookup has to find all P
elements, then find all DIV elements within P
and then find all B
elements within DIV. The deeper the nesting the more lookups it needs to do. Further, it might find all P > DIV
only to find that none of them have B
and it will have wasted time looking through all P > DIV
matches.
Lookups by ID are faster because IDs are guaranteed to be unique so the DOM can store them as hash tables which has very fast lookups. In terms of jQuery the implementation might be slightly different, however, document.getElementById has the fastest lookup time so $('#my_node_id')
should also be quite fast.
Consequently, if your node doesn't have an ID, you can find the nearest ancestor that does and find the node relative to that ancestor
#my_node_id > div > b
because the look up only needs to happen under the sub-tree of #my_node_id
it will be faster than p > div > b