Posted by & filed under Uncategorized.

Today’s topic is going to be a basic look at the jQuery Selector system.  This is one of the most widely used feature of jQuery and is one of the features that will save you the most time from regular JavaScript.

Generally when you use JavaScript and you want to select an element you would type the following code:


document.getElementById('youritem');

That does not look like a lot of code, and really it isn’t. However it does nothing at all. If you wanted to change the contents of that element you would do something like this:


document.getElementById('youritem').innerHTML = 'Hello World!';

Again not a lot of code and it does do something small. The jQuery equivalent of this would be:


$('#youritem').html('Hello World!');

You can see that this did save you a fair amount of typing. I don’t know about you but I really hate typing document.getElementById. It is a lot of typing that is made so much nicer with jQuery. Now let’s take a deeper look into how the selector works in jQuery.

$('#dom_id') – This will select the element in the HTML page whose id attribute is set to “dom_id”. Notice how this follows the CSS standards. For people who use proper HTML coding this will return only one element. If you have more than one element that has an id attribute set to “dom_id” it will return all those elements.

$('.dom_class') – This will select the elements in the HTML page whose class is set to “dom_class”. Again, notice how this follows the CSS standards.

$('.dom_class:first') – This selects the first element in the HTML page whose class is to “dom_class”.

$('.dom_class:last') – This selects the last element in the HTML page whose class is to “dom_class”.

$('.dom_class:even') – This selects the even numbered occurrences of elements in the HTML page whose class is to “dom_class”.

$('.dom_class:odd') – This selects the odd numbered occurrences of elements in the HTML page whose class is to “dom_class”.

$('.dom_class:gt(2)') – This selects the 3rd and higher occurrences of elements in the HTML page whose class is to “dom_class”. So if there are 5 total occurrences of .dom_class this will return 3rd, 4th, and 5th occurrences.

$('.dom_class:lt(5)') – This selects the first 5 occurrences of elements in the HTML page whose class is to “dom_class”.

$('*') – This will return every element in the HTML page.

This will cover about 80% of all the different selectors you will use day to day with jQuery. For a more complete list of all the different kinds of selectors you can reference the jQuery Selector API at: http://docs.jquery.com/Selectors. Feel free to post any questions you have in the comments.

Comments are closed.