Accessing HTML Elements - jQuery and JavaScript Phrasebook (2014)

jQuery and JavaScript Phrasebook (2014)

4. Accessing HTML Elements

The most important part of dynamic web development is the ability to access the DOM elements quickly and efficiently. JavaScript inherently provides functionality to access the DOM elements. This JavaScript feature can be useful at times, but this is the area where jQuery really stands out. At times you will need to use JavaScript methods to access the DOM elements, but when possible I recommend using jQuery.

The phrases in this chapter cover both the JavaScript and jQuery selector methods to find DOM elements.

Finding HTML Elements in JavaScript

There are three ways to find HTML elements using JavaScript. You can search for them by the ID attribute name, by the class name, or by the tag type. The following code shows an example of defining an HTML <div> element so that each of these methods can use it:


<div id="myDiv" class="myClass">Content</div>


By adding the ID and class attributes, you can use those values of "myDiv" and "myClass" to search for the <div> element.

Finding DOM Objects by ID


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


The simplest method to find an HTML element is to use the value of the id attribute with the document.getElementById(id) function. The document.getElementById(id) function searches the DOM for an object with a matching id attribute. If that object is found, the function returns the DOM object.

Finding DOM Objects by Class Name


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


You can also search for HTML elements by their class attribute using the document.getElementsByClassName(class). This function returns an array 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.

Finding DOM Objects by Tag Name


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


Another way search for HTML elements is by their HTML tag using the document.getElementsByTagName(tag). This function searches the document for all DOM objects that have the specified tag name and returns them in an array. You can then iterate over that array using a JavaScript loop and access or apply changes to each DOM element.

Using the jQuery Selector to Find HTML Elements

Unlike JavaScript, jQuery allows you to find HTML elements in countless ways using selectors. Yes, just like CSS selectors. In fact, most jQuery selectors are based on the CSS selectors, thus providing a more seamless transition between the two.

As demonstrated by the phrases in the upcoming sections, jQuery selectors make it easy to select just about any group of HTML elements. Keep in mind that jQuery selectors return jQuery objects that represent a set of DOM objects, not a direct array of DOM objects.

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


$("#myElement")



Watch out!

There are several meta characters 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 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").


Applying Basic jQuery Selectors


$("*"); //selects all elements
$(".myClass"); //selects elements with class="myClass"
$("#myDiv"); //selects the element with id="myDiv"
$("div"); //selects <div> elements
$("div, span, p"); //selects <div>, <span>, and <p> elements
$("div.myClass"); //selects <div> elements with class="myClass"


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 4.1 lists some examples to show you how to define some of the basic selectors.

Image

Image

Table 4.1 Examples of Using Basic jQuery Selectors

Selecting Elements Based on HTML Attributes


$("input[value=0]"); //selects <input> with value="0"
$("p[class*=my")//selects elements "my" in classname
$("img[src^='icons\\/']");
//selects <img> elements where src starts with "icons/"
$("input[value!='default']");
//selects <input> elements where the value is not "default"
$("p[id]"); //selects <p> elements that have id set
$("p[id][class$=Menu");
//selects <p> elements with idset and
//classname ending with "Menu"


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 4.2 shows some of the ways that you can apply attribute selectors.

Image

Image

Table 4.2 Examples of Using Attribute jQuery Selectors

Selecting Elements Based on Content


$("p:contains('free')");
//selects <p> elements that contain "free
$("div:has(span)");
//selects <div> elements that contain <span> elements
$("div:empty");
//selects <div> elements with no content or children
$("div:parent");
//selects <div> elements that have at least some content


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 4.3 shows examples of using content selectors.

Image

Table 4.3 Examples of Using Content jQuery Selectors

Selecting Elements by Hierarchy Positioning


$("div span");
//selects <span> elements with a <div> ancestor
$("div.menu > span");
//selects <span> elements whose immediate parent
//is a <div> with class="menu"
$("label + input.textItem");
//selects <input> elements with class="textItem" that
//are immediately preceded by a <label>
$("#menu ~ div");
//selects all <div> elements that are siblings of
//the element with id="menu"


An important set of jQuery selectors is the hierarchy selectors. These selectors allow you to select HTML elements based on the DOM hierarchy. This allows 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 4.4 shows some examples of hierarchy selectors.

Image

Image

Table 4.4 Examples of Using Hierarchy jQuery Selectors


By the way

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 just $("menu") because it would limit the search to the <div> element before checking from the menu class attribute.


Selecting Elements by Form Status


$("input:checked");
//selects <input> elements that are checked
$("option:selected");
//selects <option> elements that are selected
$("#myForm :focus");
//selects the element in the #myForm <form>
//that currently has the focus
$("input:disabled");
//selects <input> elements that are currently disabled


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

Image

Table 4.5 Examples of Using Attribute jQuery Selectors

Selecting Elements Based on Visibility


$("div:visible");
//selects <div> elements that are currently visible
$("div:hidden");
//selects <div> elements that are currently hidden


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

Image

Table 4.6 Examples of Using Attribute jQuery Selectors

Applying Filters in jQuery Selectors


$("tr:even"); //selects the even <tr> elements
$("li:odd"); //selects the odd <li> elements
$("div:first"); //selects the first <div> element
$("div:last"); //selects the last <div> element
$(":header"); //selects <h1>, <h2>, ... elements
$("div:eq(5)"); //selects the 6th <div> element
$("li:gt(1)"); //selects <div> elements after the first two
$("li:lt(2)"); //selects the first two <div> elements
$(":animated"); //selects elements currently animating


Often you need to refine your jQuery selectors 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 that the selector returns. Table 4.7 shows some examples of adding filters to selectors.

Image

Image

Table 4.7 Examples of Using Filtered jQuery Selectors

Chaining jQuery Object Operations


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


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

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 previous code took five lines to accomplish all its tasks. The following statement of chained jQuery operations does the same things but with only a single statement:


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


Because each of the operations returns 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.

Navigating jQuery Objects to Select Elements

Another important set of methods attached to a jQuery object is the DOM traversing methods. DOM traversal allows you to select elements based on their relationship to other elements. A couple of examples of DOM traversal are accessing all <p> elements that are children of <div>elements and finding a <label> element that is a sibling of an <input> element.

jQuery object provides 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. The following phrases provide some examples of traversing the DOM elements in jQuery objects to get to other sets of objects.

Getting the Children of Elements


$("div").children("p");
//selects the <p> elements that are direct children
//of <div> elements


The .children([selector]) method returns a jQuery object representing the children of the elements represented by the current object. You can specify an optional selector that limits the results to only include children that match the selector.

Getting the Closest Elements


$("p.menu").closest("div");
//selects the closest <div> ancestor for <p>
//elements that have class="menu"


The .closest(selector,[context] or object or element) method returns a jQuery object representing the first element that matches the argument that is passed in. The argument can be a selector, a selector with context of where to begin searching, a jQueryobject, or a DOM object. The search begins at the current set of elements and then searches ancestors.

Getting the Elements Contained


$("div").contents();
//selects all the immediate child elements in <div> elements
$("select").contents();
//selects all the <option> elements in <select> elements


The .contents() returns a jQuery object representing the immediate children of the current set of elements. This is especially useful when getting all the <li> elements in a list or the <option> elements in a <select> block.

Finding Descendant Elements


$("table").find("span")
//selects all <span> elements contained
//somewhere in <table> elements
$("#myForm").find("input")
//selects all <input> elements contained
//somewhere in element #myForm


The .find(filter) method returns a jQuery object representing descendants of the current set that match the filter supplied. The filter can be a selector, a jQuery object to match elements against, or an element tag name.

Example: Selects all <span> elements contained somewhere in <table> elements.

Getting Siblings That Come After Selected Objects


$("#title").next("p");
//finds the element with id="title" and selects
//the very next <p> element that is a sibling
$("p:first").nextAll();
//selects the first <p> element that it finds and
//then selects all the <p> siblings to that element
$("p:first").nextUntil("ul");
//selects the first <p> element that it finds and
//then selects all the siblings until it finds a <ul> element


The .next([selector]) method returns a jQuery object representing the next sibling of each element in the current set. If the optional selector is provided, the next sibling is added only if it matches the selector.

The .nextAll([selector]) method returns a jQuery object representing all the following sibling objects of each element in the current set. Also accepts an optional selector.

The .nextUntil([selector] or [element] [,filter]) method returns a jQuery object representing all the sibling objects after each element in the current set, until an object matching the element or selector argument is encountered. The first argument can be a DOMobject or a selector. The second optional argument is a filter selector to limit the items returned in the results.

Getting the Positioning Parents


$("#notify").offsetParent();
//selects the element with id="notify" and then selects
//the ancestor that is used to position that element


The .offsetParent() method returns a jQuery object representing the closest ancestor element that has a CSS position attribute of relative, absolute, or fixed. This allows you to get the element used for positioning, which becomes critical when you need to get the size of the position container.

Finding the Parent or Ancestors of Selected Items


$("div#menu").parent();
//selects the <div> element with id="menu" and
// then finds its immediate parent
$("#data").parents("div");
//selects the element with id="data" and then
//returns a set with all <div> ancestors
$("#data").parentsUntil("#menu");
//selects the parents of #data until
//it finds the one with id="#menu"


The .parent([selector]) method returns a jQuery object representing the immediate parent objects of each of the elements represented in the current set. An optional selector argument allows you to limit the results to those parents matching the selector.

The .parents([selector]) method returns a jQuery object representing the ancestors of each of the elements represented in the current set. An optional selector argument allows you to limit the results to those parents matching the selector.

The .parentsUntil([selector] or [element] [, filter]) method returns a jQuery object representing the ancestors of each of the elements represented in the current set, until an object matching the element or selector argument is encountered. The first argument can be an element tag name or a selector. The second optional argument is a filter selector to limit the items returned in the results.

Getting the Previous Siblings


$("p#footer").prev("p")
//Finds the <p> element with id="footer" and
//selects the previous <p> element that is a sibling
$("div#footer").prevAll("div");
//selects the <div> element with id="footer" and then
//selects all the <div> siblings prior to that element
$("div#footer").prevUntil("div#header");
//finds the <div> element with id="footer" and then
//selects all prior siblings until #header is found


The .prev([selector]) method returns a jQuery object representing the previous sibling of each element in the current set. If the optional selector is provided, the previous sibling is added only if it matches the selector.

The .prevAll([selector]) method returns a jQuery object representing all the previous sibling objects of each element in the current set. It also accepts an optional selector.

The .prevUntil([selector] or [element] [,filter]) method returns a jQuery object representing all the sibling objects that come before each element in the current set, until an object matching the element or selector argument is encountered. The first argument can be a DOM object or a selector. The second optional argument is a filter selector to limit the items returned in the results.

Getting Siblings


$(".menu").siblings("span")
//selects all <span> elements that are
//siblings to elements with class="menu"


The .siblings([selector]) method returns a jQuery object representing all the sibling objects for each element in the current set. An optional selector argument allows you to limit the results to those siblings matching the selector.