Targeting specific elements on a page is one of the most common tasks performed in DOM scripting. Essentially, jQuery uses the CSS selection pattern to find elements. This makes it ridiculously easy to target any element on a page.
This SitePoint guide on CSS selectors has more in-depth information on how to select elements with CSS.
So for example, if you wanted to target the LI elements within this block of HTML:
<div id="nav"> <ul> <li>This is a list item</li> <li>This is a list item</li> </ul> </div>
The CSS selector would look like:
#nav li {display:block;}
So with jQuery, you would use that same selector ( #nav li ):
$('#nav li').css('display', 'block');
To preform this task with plain Javascript, you would have return all the LI’s into an array, loop through that array, and apply the CSS to each element. See below:
var LIs = document.getElementById('nav').getElementsByTagName('LI');
for(var i=0; i<LIs.length; i++){
LIs[i].style.display = 'block';
}
Note that setting CSS with JavaScript is not something you would necessarily want to do. Separating behavior and presentation is a very important practice to follow. I’m just using it as an easily understandable example.
jQuery also offers ways to filter your selection. Some common filtering tasks (that I run into often) include:
- Adding zebra-styling to rows using even or odd filters
- Selecting all except for a certain element using .not()
- If using borders on lists, using first and last to remove top and bottom borders of first and last list items.
For a in-depth guide to jQuery’s Selectors, check out their API.
