Hour 8. Navigating and Manipulating jQuery Objects and DOM Elements with jQuery


What You’ll Learn in This Hour:

Image Chaining jQuery operations together for efficiency

Image Ways to filter the DOM elements in a jQuery object

Image Methods to use jQuery objects to traverse the DOM

Image Iterating through each element in the jQuery object set


jQuery selectors return a jQuery object that represents zero or more elements that match the selector definition. Simple selectors are great for a lot of different things. However, as your web pages become more complex, you will find that the selectors do not do everything that you need.

jQuery objects provide additional functionality and enhance the selector results by allowing you to easily refine the list of DOM elements represented, navigate the DOM tree to find other elements, and manipulate the values of the HTML elements. The following sections cover how to chain jQuery operations together to efficiently find, filter, and navigate around the DOM elements in the web page.

Chaining jQuery Object Operations

One of the great things about jQuery objects is that you can chain multiple jQuery operations together into a single statement. Each consecutive statement will operate on the results of the previous operation in the chain. This can help reduce and simplify your selectors and reduce the amount of class and ID definitions required in your CSS.

Think of the results of the chained jQuery operations as a stack of jQuery objects, with each object representing a set of DOM elements. Each operation in the chain will place a jQuery object onto the stack, but the current operation will be applied only to the top jQuery.

To help illustrate this, consider the following statements. The code first finds the <div> element with id="content" and then finds the first <p> element inside and changes the font-weight to bold. Then it finds the <span> elements inside the <p> and sets the color to red:

var $contentDiv = $("div#content");

var $firstP = $contentDiv.children("p:first");
$firstP.css("font-weight","bold");
var $spans = $firstP.children("span");
$spans.css("color","red");

The code above took five lines to accomplish all the tasks it does. The following single line of chained jQuery operations does the same things but with only a single line:

$("div#content").children("p:first").css("font-weight","bold").children("span"). css("color","red");

Because each of the operations return a jQuery object, you can chain as many jQuery operations together as you would like. Even though the .css() operation is designed to alter the DOM objects and not find them, it still returns the same jQuery object so you can perform other operations on the results.

Filtering the jQuery Object Results

jQuery objects provide a good set of methods that allow you to alter the DOM objects represented in the query. Reducing the results is helpful when you are trying to pinpoint a specific set of elements within a jQuery selector result. Table 8.1 provides some examples of chaining jQuery selectors.

Image

TABLE 8.1 jQuery Object Methods with Examples That Filter the DOM Elements Represented


Tip

The jQuery selectors that are the same as the CSS selectors are able to use the native DOM method querySelectorAll(), which has some advanced optimizations on DOM objects. Other jQuery selectors cannot take advantage of that optimization, so it is better to use a CSS-based selector first and then add the filter as a chained selector. For example, rather than using $("div:animated"), you should use $("div").filter(":animated). http://api.jquery.com/category/selectors/jquery-selector-extensions/


Traversing the DOM Using jQuery Objects

Another important set of methods attached to the jQuery object are the DOM traversing methods. DOM traversal enables you to select elements based on their relationship to other elements.

The DOM is sometimes referred to as the DOM tree because it is organized in a tree structure, with the document as the root and nodes that can have parents, siblings, and children. To visualize this better, check out the following HTML code:

<body>
  <div>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <ul>
       <li>Item 1</li>
        <li>Item 2</li>
      </ul>
 </div>
</body>

The <p> element and <ul> element are siblings to each other, and they are all children of the <div> element. The <div> element is the parent of the <p> and <ul> elements, and the <ul> element is the parent of the <li> elements, and so forth.

jQuery DOM traversing methods enable you to move from one layer in the DOM to another to select elements—for example, if you want to access all <p> elements that are children of <div> elements, or if you want to find a <label> element that is a sibling of an <input> element.

jQuery objects provide an incredible set of methods that allow you to traverse the DOM in almost innumerable ways by allowing you to use the current selection of DOM elements in the jQuery object to select other sets of DOM elements in the tree. Table 8.2 lists the methods that you can use to traverse the DOM.

Image
Image
Image
Image

TABLE 8.2 jQuery Object Methods with Examples That Allow You to Traverse the DOM to Select Elements

Looking at Some Additional jQuery Object Methods

When filtering the jQuery object or using it to traverse the DOM, there are some additional methods that you should be aware of. Table 8.3 lists a set of methods that you can use in conjunction with filtering and traversing elements, to iterate through the DOM elements in the jQuery object, add additional elements to the set, end filtering, and test items. You will find that you’ll use these methods more and more frequently as your jQuery code becomes more natural to you.

Image
Image

TABLE 8.3 A Few Additional Methods and Examples That Allow You to Work with jQuery Objects


Note

When using functions with jQuery methods that iterate through the DOM elements, you can use the this keyword to access the current DOM object that is being iterated on. This is a DOM object and not a jQuery object. If you need to use the jQuery form of the DOM object, then use $(this) instead. Keep in mind, though, that it takes work in the browser’s rendering engine to build the jQuery form of the DOM object, so create the jQuery form only if you want the functionality that is provided.


Using .each()

The .each(function) method is one of the most important jQuery object methods because it allows you to traverse all elements in the jQuery set and perform actions on each of them individually. This is different from just applying the same action to all items in the query.

The .each() method allows you to specify a function that will be run for each element in the jQuery object set. The function will be passed an index number as the first argument. Inside the function, the this variable will point to the current DOM element.

The following snippet of code illustrates using .each(). It iterates through all paragraph elements and sets the content, including the index number of the element:

$("p").each(function (idx){
    $(this).html("This is paragraph " + idx);
  });

Notice that idx is passed in as an index number, 0 for the first <p> element, 1 for the second, and so on. Also note that this was converted to a jQuery object using $(this) so that the .html() method could be called.

Using .map()

The .map(function) method also iterates through each element in the jQuery object set. Although very similar to .each(), there is one big difference, which is that .each() will return the same jQuery object, but .map() will return a new jQuery object with the values returned by each iteration.

The following snippet of code illustrates using .map(). It will iterate through all <li> elements and return a comma-separated string of the elements’ text:

var liValues = $("li").map(function (idx){
    return $(this).html();
  }).get().join(",");

Notice that for each iteration, the function returns the HTML content in the <li> element. You call .get() to return a JavaScript array version of the new jQuery object returned by .map() and then call .join(",") on that array to build the comma-separated string.

Summary

In this hour, you learned about using jQuery and JavaScript objects to find and navigate through the DOM elements. This adds a critical piece in implementing dynamic code because often you will want to act, not on the elements that you search for, but for elements related to them.

You learned how to chain jQuery requests together to apply multiple operations to the same set of DOM elements. This reduces the number of statements required in your scripts.

You also learn how to iterate through the DOM element set associated with the jQuery objects returned by the selector. This allows you to apply a different set of operations to each individual element in a set without the need to look each one up individually.

Q&A

Q. What is the difference between $("div:eq(n)") and $("div").eq(n)?

A. The biggest difference is that .eq() enables you to specify a negative number and count backward from the end. For example, .eq(-1) is the last element in the list. :eq() does not allow negative indexes.

Q. How many jQuery options should be chained together?

A. Good question. It depends on the circumstances. It is really a question of performance versus readability/reusability. Keep in mind that there is a bit of code behind each jQuery lookup, so the more you can use the same jQuery stack, the better off you are. At some point, what is really in the current stack can become confusing; however, at that point you should save yourself future headaches and move on. A better approach is to break the operations into separate groups that can be reused and then define variable names for those.

Workshop

The workshop consists of a set of questions and answers designed to solidify your understanding of the material covered in this hour. Try to answer the questions before looking at the answers.

Quiz

1. What jQuery method would you use to filter out elements that have a <p> element as a child?

2. What jQuery method would you use to get all sibling <p> elements before an element with id="middleEarth"?

3. What is the difference between .map() and .each()?

Quiz Answers

1. .has("p");

2. $("#middleEarth").prevAll("p");

3. .map() is used to iterate through the set of elements and return a new object containing the results of the specified function of each iteration. .each() will just iterate through the elements applying the function specified.

Exercise

1. Extend the HTML code in hour0801.html to include more <div> sections like the others. Notice that the same functionality is automatically applied to each.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset