jQuery To The Rescue Part 2

So what are jQuery selectors about. Selectors provides a very easy way of gaining access to any HTML element on the DOM. Now this might not make sense at the moment, so let me give you 2 examples.

The scenario: your manager runs into the office screaming “I’ve got a set of UL elements and I need you to print the 3rd LI element to the screen!”

The HTML

<ul>
<li>Test 1</li>
<li>Test 2</li>
<li>Test 3</li>
<li>Test 4</li>
<li>Test 5</li>
</ul>

The javascript code:

1
2
3
4
5
6
7
8
9
10
11
// Get the LI elements
var ul = document.getElementById('testElement');
var items = ul.getElementsByTagName("li");
 
// Loop through each of the li elements
for (var i = 0; i &lt; items.length; ++i) {
 
// Once you get to the third element alert the contents of the li element
if(i == 2)
alert( items[i].innerHTML );
}

The jQuery code:

1
2
// Alert the content of the third li element of the UL with the id testElement
alert( $('#testElement li:nth-child(3)').html() );

Compare the two examples above and decide which method you prefer. If it’s the latter, go to http://api.jquery.com/category/selectors for further reading.

This entry was posted in Managed Hosting. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>