Quick Tips – jQuery: Giving your selectors some context
Quick Tips is a series of posts designed to show some quick html, css and php tips that you may find useful in your every day work or personal projects.
The jQuery function allows for a second, lesser known about, parameter which tells the function to only search for the element within the context of the given element.
- List item 1
In this scenario the selector will navigate through the menu unordered list and select the list item with “List item 2″ in it, having never seen the other unordered list.
Instead of having to work its way through the entire DOM, containing perhaps several hundred of the same element, the function can search within the smaller search area and provide results faster and more accurate.
If you wish to submit a quick tip to this section please contact me..
Related posts:
Leave a comment
$('li','ul.menu'); is functionally equivalent to $('ul.menu li'); Far more useful, I find, are the is the ability to pass another jQuery object as the second parameter, e.g. the results from an earlier query, or a dom object, such as the document object of an external xml file retrieved from an ajax query.
var menu = $('ul.menu');
$('li', menu);
Seb
July 13, 2010
Actually there is a subtle difference.
The way $('ul.menu li') would work would be to search through the DOM to find all list items within a located ul.menu.
The other way of doing it – $('li','ul.menu') would only target the unordered list when performing the search.
andygirvan
July 13, 2010
Additionally there is a great stackoverflow article about this:
http://stackoverflow.com/questions/2421782/perf…
andygirvan
July 13, 2010