The Power of jQuery Selectors: Selecting Elements

jQuery provides a myriad of ways to select DOM elements: you can select elements by attributes, element type, element position, CSS class, or a combination of these. The syntax for selecting elements is as follows:

$(selector,[context])

or

jQuery(selector, [context])

To select elements by tag name, use the tag name in the selector. For example, $(“div”) retrieves all of the divs in a document. Running the previous example in a “jQuerified” jconsole, you can see the returned object in the Firebug window.

In the next example, the same div selector expression is used, with three empty divs in the body. With the length property, you can verify that the selector returns three elements using a console.log.

<!DOCTYPE html>

<html>

<head>

<script src=”http://code.jquery.com/jquery-1.7.1.js”>

</script>

<script>

$(document).ready(function(){

var wrappedElements = $(“div”);

console.log(wrappedElements.length);

});

</script>

</head>

<body>

<div id=”1″></div>

<div id=”2″></div>

<div id=”3″></div>

</body>

</html>

Code snippet is from tag-selector.txt

Another way to select elements is by their ID attribute. For example, $(“div#elementld”) selects all divs with an ID of elementld. In general, the format for selecting by ID is the element name, followed by a hash (#), and the ID to match against. The following code example illustrates this with a code sample that selects an element with the ID of myList.

<!DOCTYPE html>

<html>

<head>

<script src=”http://code.jquery.com/jquery-1.7.1.js”>

</script>

<script>

$(document).ready(function(){

var wrappedElements = $(“ul#myList”);

console.log(wrappedElements.length);

});

</script>

<body>

<div id=”main”>

<ul id=”myList”>

<li>foo</li>

<li>bar</li>

</ul>

</div>

</body>

</html>

Code snippet is from id-selector.txt

You can also get all of the elements in the DOM using the all selector (*) as demonstrated in the next snippet. The resulting length is 9 elements.

<!DOCTYPE html>

<html>

<head>

<script src=”http://code.jquery.com/jquery-1.7.1.js”>

</script>

<script>

$(document).ready(function(){

var allElements = $(“*”);

console.log(allElements.length);

});

</script>

<body>

<div id=”main”>

<ul id=”myList”>

<li>foo</li>

<li>bar</li>

</ul>

</div>

</body>

</html>

Code snippet is from all-selector.txt

By default, when selecting elements, jQuery searches through the entire DOM tree. At times, you may want to search through a subtree of the DOM. You can accomplish this by passing an optional second parameter to the jQuery function to give the selection a context. For example, say you have a series of links you’d like to retrieve from just a single div in the DOM. You could do the following:

$(“a”,”js_links#div”);

Source: Otero Cesar, Rob Larsen (2012), Professional jQuery, John Wiley & Sons, Inc

Leave a Reply

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