Hour 7. Accessing DOM Elements Using JavaScript and jQuery Objects


What You’ll Learn in This Hour:

Image The difference between jQuery and JavaScript DOM objects

Image How to tell if an object is jQuery or DOM

Image How to get a jQuery object from a DOM object

Image How to get a DOM object from a jQuery object

Image How to use jQuery selectors to quickly find DOM elements


The most important part of dynamic web development is the capability to access the DOM elements quickly and efficiently. JavaScript inherently provides functionality to access the DOM elements. It can be useful at times; however, this is the area where jQuery really stands out and you understand the need for jQuery on top of JavaScript.

In the following sections, you learn about the basic structure of jQuery and JavaScript DOM objects, how to determine whether an object is jQuery or DOM, and how to switch between them. The rest of the hour discusses methods you can use to find and access the DOM elements using jQuery and JavaScript.

Understanding DOM Objects Versus jQuery Objects

You need to understand the difference between DOM objects and jQuery objects and how to manipulate and use both to be effective when creating dynamic web pages. In this section, you learn about these types of objects and how to navigate between them.

Introducing JavaScript DOM Objects

DOM objects are the objects that the web browser is using to render elements on the web page. Consequently, DOM objects have a great deal of functions and attributes. The advantage with working with DOM objects is that you have direct access to everything you need to manipulate the HTML element.

The disadvantage of DOM objects is that most of the attached functions and attributes are things that the browser needs and are not necessarily useful when you’re working with JavaScript. That means that the DOM object has a lot of properties and methods that encumber your debugging environment, such as Firebug or other JavaScript consoles.

Table 7.1 provides a list of some of the important attributes and methods of DOM objects that you should be aware of. The list is not comprehensive; it is intended to give you an idea of things that you can access from a DOM object.

Image
Image

TABLE 7.1 Some of the More Commonly Used Attributes/Methods Attached to DOM Objects

Introducing jQuery Objects

jQuery objects are basically wrapper objects around a set of DOM elements. The jQuery objects are still JavaScript objects and provide access to the DOM elements—however, in a much different, much easier, and often much more effective way.

The most important thing to remember is that a jQuery object may represent a single DOM object or it may represent a set of many DOM objects. So if you apply an operation on the jQuery object, it may apply to many DOM objects.

The biggest advantage to jQuery objects is how easy it is to search HTML elements in a web page. Another advantage is that the jQuery library wraps methods and attributes specifically to make it easier for JavaScript and jQuery developers to manipulate and work with different groups of objects. Calling a method on a jQuery object can apply to one or many DOM elements without the need to iterate through a list.

Table 7.2 provides a list of some of the important methods of jQuery objects that you should be aware of. The list is not comprehensive; it is intended to give you an idea of things that you can access from a jQuery object.

Image

TABLE 7.2 Some of the More Commonly Used Methods Attached to jQuery Objects

Determining Whether an Object Is DOM or jQuery

Occasionally, you find yourself in a situation where you have an object and you are not sure whether it is a jQuery object, a DOM object, or some other JavaScript object. There is a simple way to tell the difference.

To tell whether an object is a jQuery object, use the following if syntax to check to see whether the object has the jquery attribute:

if( obj.jquery ) {
  ...

To tell whether an object is a DOM object, use the following if syntax to check to see whether the object has the nodeType attribute:

if( obj.nodeType ) {
  ...

Changing an Object from DOM to jQuery and Back

What do you do if you have a jQuery object but you want to use code intended for DOM objects, or vice versa? The answer is to convert the object to the other type.

The .get() method returns the JavaScript version of the jQuery element set in the form of an array of DOM objects. Use the following code to call the get() function that returns the DOM object of the HTML element represented by the jQuery object:

var domObj = jqueryObj.get();

Conversely, the $() or jquery() method creates a new jQuery object from JavaScript. Use the following code to execute the $() function to wrap the DOM object as a jQuery object:

var jqueryObj = $(domObj);

Accessing DOM Objects from JavaScript

To be able to manipulate HTML elements from JavaScript, you first need to gain access to the DOM object. You can use a few different methods to do that.

Finding DOM Objects by ID

The simplest is to find an HTML element using the value of the id attribute using the getElementById(id) function. getElementById(id) searches the DOM for an object with a matching id attribute.

For example, the following code searches for the HTML element with id="container":

var containerObj = document.getElementById("container");

Finding DOM Objects by Class Name

You can also search for HTML elements by their class attribute using the getElementsByClassName(class). This function returns a list of DOM objects with matching class attributes. You can then iterate over that list using a JavaScript loop and apply changes to each DOM element.

For example, the following retrieves a list of HTML elements with class="myClass" and then iterates through them:

var objs = document.getElementsByClassName("myClass");
for (var i=0; i<objs.length; i++){
  var htmlElement = objs[i];
  ...
}

Finding DOM Objects by Tag Name

Another way to search for HTML elements is by their HTML tag, using the getElementsByTagName(tag). This function returns a list of DOM objects with matching HTML tag. You can then iterate over that list using a JavaScript loop and apply changes to each DOM element.

For example, the following code retrieves a list of the <div> HTML elements and then iterates through them:

var objs = document.getElementsByClassName("div");
for (var i=0; i<objs.length; i++){
  var htmlElement = objs[i];
  ...
}

Using jQuery Selectors

Unlike JavaScript, jQuery enables you to find HTML elements in countless ways using selectors. Yes, just like CSS selectors. In fact, most of the jQuery selectors were taken from CSS, providing a more seamless transition between the two.

As you will find in upcoming sections, jQuery selectors make it very easy to select just about any group of HTML elements. Keep in mind, though, that jQuery selectors return jQuery objects, not DOM objects.

jQuery selector syntax is very straightforward. After the jQuery library is loaded, use $(selector). For example:

$("#myElement")


Caution

Several meta characters are used in jQuery selector syntax. If you want to use any of the meta characters, such as !"#$%&'()*+,./:;<=>?@[]^`{|}~ ), as a part of a class/ID/name, you will need to escape the character with \ two backslashes. For example, if you have an element with id="my.element", you would use the selector $("#my\.element").


As with CSS selectors, the best way to introduce you to jQuery selectors is to show you some examples. The following sections take you through some examples of different types of jQuery selectors. These sections only scratch the surface. You can go to the following location to review the selector documentation when you get a chance:

http://api.jquery.com/category/selectors/

Applying Basic Selectors

The most commonly used selectors are the basic ones. The basic selectors focus on the id attribute, class attribute, and tag name of HTML elements. Table 7.3 list some examples to show you how to define some of the basic selectors.

Image

TABLE 7.3 Examples of Using Basic jQuery Selectors

Applying Attribute Selectors

Another way to use jQuery selectors is to select HTML elements by their attribute values. It can be a default attribute or one that you have added to the HTML elements. Attribute values are denoted in the selector syntax by being enclosed in [] brackets. Table 7.4 shows some of the ways that attribute selectors can be applied.

Image
Image

TABLE 7.4 Examples of Using Attribute jQuery Selectors

Applying Content Selectors

Another set of useful jQuery selectors are the content filter selectors. These selectors allow you to select HTML elements based on the content inside the HTML element. Table 7.5 shows examples of using content selectors.

Image

TABLE 7.5 Examples of Using Content jQuery Selectors

Applying Hierarchy Selectors

An important set of jQuery selectors are the hierarchy selectors. These selectors allow you to select HTML elements based on the DOM hierarchy. This enables you to write dynamic code that is more content aware by only selecting elements based on parents, children, or other elements around them in the DOM tree. Table 7.6 shows some examples of hierarchy selectors.

Image

TABLE 7.6 Examples of Using Hierarchy jQuery Selectors


Note

It is always best to be as specific as possible when designing your jQuery selectors. For example, if you want to select all the span elements with class="menu" and these elements are only under the <div> element with id="menuDiv", then $("div#menuDiv .menu") would be much more efficient than $(".menu") because it would limit the search to the <div> element before checking from the menu class attribute.


Applying Form Selectors

An extremely useful set of selectors when working with dynamic HTML forms are the form jQuery selectors. These selectors enable you to select elements in the form based on the state of the form element. Table 7.7 shows some examples of form selectors.

Image

TABLE 7.7 Examples of Using Form jQuery Selectors

Applying Visibility Selectors

If you are using visibility to control the flow and interactions of your web page components, using the visibility jQuery selectors makes it simple to select the HTML elements that are hidden or visible. Table 7.8 shows some examples of visibility selectors.

Image

TABLE 7.8 Examples of Using Visibility jQuery Selectors

Applying Filtered Selectors

Often you will need to refine your jQuery selectors down to a more specific subset. One way to accomplish that is to use filtered selectors. Filtered selectors append a filter on the end of the selector statement that limits the results returned by the selector. Table 7.9 shows some examples of adding filters to selectors.

Image
Image

TABLE 7.9 Examples of Using Filtered jQuery Selectors

Summary

In this hour, you learned about using jQuery and JavaScript objects to find and access DOM elements. This is the most critical piece of dynamic programming, because you must be able to provide efficient access to the DOM elements to be able to manipulate them dynamically. You learned the basic syntax and structure of JavaScript DOM objects as well as a few of the methods and attributes attached to those objects.

Q&A

Q. When should I use the getObjectById() rather than $("#id")?

A. It’s likely that you will rarely use getObjectById(). The only times you might use it is when you don’t want to take the time to link the jQuery library to your HTML docs. jQuery is so much more extensible.

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. How to would you convert a DOM object named myDiv into a jQuery object?

2. True or False: A jQuery selector returns a list of DOM objects.

3. How can you tell if an object is a jQuery object?

4. What jQuery selector would you use if you wanted all elements with class="heading"?

5. What jQuery selector would you use to get all <p> elements that are children of <div> elements?

6. How can you get a JavaScript array of the DOM elements represented in a jQuery object?

Quiz Answers

1. Use $(myDiv) to create a new jQuery object with the DOM element as the only item in the set.

2. False. A jQuery selector returns a jQuery object that contains a set of DOM elements.

3. Test to see whether it has the jquery property set.

4. $(".heading")

5. $(div p)

6. Use the get() method on the jQuery object.

Exercise

1. Add an additional button to the example in hour0702.html that will select only the first and last planets in the list. You will need to add the HTML and JavaScript code necessary to do so.

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

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