To manipulate the DOM, you need to know how to access it and to obtain references to the elements you want to manipulate. In the next section you look at altering the DOM, but first you need to get elements from the DOM so you can work with them.
NOTE THE DOCUMENT OBJECT MODEL AS A FAMILY TREE
The DOM is essentially a collection of nodes arranged in a tree. All the nodes are related to each other. They are one big happy family of children, siblings, parents, grandparents, grandchildren, and so on. This essence of a family tree represents the hierarchy of the DOM and is important to understand as you manipulate the DOM through code.
You have a few choices when it comes to using JavaScript to access the DOM. You can access DOM elements through a global object provided by the browser, called document, or through the elements themselves after you obtain a reference to one. Table 1-2 outlines the core native methods used for selecting elements in the DOM.
TABLE 1-2 Methods available for selecting DOM elements
Method Usage description
getElementById Gets an individual element on the page by its unique id attribute value getElementsByClassName Gets all the elements that have the specified CSS class applied to them getElementsByTagName Gets all the elements of the page that have the specified tag name or
element name
querySelector Gets the first child element found that matches the provided CSS selector criteria
querySelectorAll Gets all the child elements that match the provided CSS selector criteria
For the most part, the methods are straightforward to use. In this section, you begin with a simple HTML document structure that you will use in many other examples in this book to highlight various concepts. Create a webpage with the HTML markup in Listing 1-2 to pro-ceed with the following examples.
ptg14200515
LISTING 1-2 HTML source to work with the DOM
<body>
<div id="outerDiv">
<p class='mainPara'>Main Paragraph</p>
<ul>
<input type="text"/><input type="submit" value="Submit"/>
</div>
</body>
This sample page is very simple, but it serves the purpose of demonstrating various ways to access elements through code. To demonstrate this functionality, you need an entry point.
Add the following script block to the head section of the webpage:
<script>
window.onload = function () { ...
} </script>
This should look familiar, but if it doesn’t, you’ll review the concepts later. For now, this code essentially tells the runtime to run your code after the window finishes loading. You can
ptg14200515 use your code to experiment with the various methods listed in Table 1-2 in this function,
starting with getElementById.
The getElementById method returns the element in the page that matches the specific ID value you pass to it. It returns null if no element on the page has the specified ID. Each ele-ment on the page should have a unique ID. For example, if you want to reference the <div>
element with the ID outerDiv, you would use the following code:
var element = document.getElementById("outerDiv");
alert(element.innerHTML);
The JavaScript alert method, which displays a message box, is used here to show whether you have actually accessed the DOM successfully. The alert isn’t all that useful in the real world but it is for development purposes. When you run the page, notice the message box from the browser with all the innerHTML contents of the <div> you selected out of the DOM with your code (see Figure 1-14).
FIGURE 1-14 A JavaScript alert demonstrating successful access to the DOM
ptg14200515 Now that you have successfully obtained a reference to your <div>, you can do anything
you want to it dynamically—just as you could have defined or applied such changes to it statically. The getElementById method is great when you know the ID of a specific element in the page that you want to work with, but in other cases you might want to do something to all the elements of a particular type—for example, all paragraph elements. In this case, the getElementsByTagName method is more appropriate. You can use the following code to get a reference to all the <p> elements:
<script>
window.onload = function () {
var paragraphs = document.getElementsByTagName("p");
alert(paragraphs.length);
} </script>
In this code, the object returned from the getElementsByTagName method is a little differ-ent; it’s a special type that acts as a wrapper to all the elements that match your parameter, called a NodeList. This object isn’t especially useful by itself. In fact, it doesn’t really provide anything useful other than a length, which lets you know how many items it contains, and the ability to access each individual item. In the preceding example, the JavaScript alert displays how many items were returned in the list (paragraphs.length). You can see that the method returned all five of the <p> elements in the page, as shown in Figure 1-15.
FIGURE 1-15 A message showing the number of <p> elements
In the same way that you could use the getElementsByTagName method to get all elements of the same type, you can use the getElementsByClassName method to get all elements of the same CSS class. This is useful when you have many elements with the same style but perhaps want to modify them at run time. This method also returns a NodeList. The following snippet demonstrates the usage:
<script>
window.onload = function () {
var paragraphs = document.getElementsByClassName("subPara");
alert("<p> elements with class subPara: " + paragraphs.length);
}
</script>
Figure 1-16 shows the output of this script.
ptg14200515
FIGURE 1-16 A message showing the number of <p> elements with the specified class name subPara This example adds a little more text to the message box so that it looks different from the previous example, but the idea is the same. All <p> elements with the subPara class assigned to them were returned in a NodeList. You can see that the call returned four HTML elements.
When selecting elements in the DOM by class name, the NodeList contains all elements whose class matches the specified class—not just elements of the same type. If, for example, you assigned the class subPara to one of your <div> elements and then ran the function again, the returned NodeList would contain the four <p> elements and the <div> element because they all have the same class. This is important when you intend to iterate over the elements and do something to them. In Figure 1-17, the same JavaScript code is run, but with an added subPara class attribute to a <div> element.
FIGURE 1-17 The same script run with a <div> assigned the class name subPara
This message box is now actually incorrect, because the NodeList contains a single
<div> element and the four <p> elements. Keep this behavior in mind concerning the getElementsByClassName method.
All the methods you have looked at so far to find elements in the DOM provide a specific implementation for a specific purpose. If you want a single element by its unique ID, you use the getElementById method; if you want to find an element or all the elements of a specific CSS class, you use the getElementsByClassName method. Now look at some examples that use the much more flexible querySelector and querySelectorAll methods.
The querySelector and querySelectorAll methods allow you to achieve most of what you’ve already done with the other methods. Both methods take a parameter in the form of a CSS
ptg14200515 selector. The querySelector method returns the first element it finds that matches the
selec-tor criteria passed to it, whereas the querySelecselec-torAll method returns all elements that match the selector criteria passed in. The elements are still returned in the form of a NodeList object.
Both methods exist not only on the document itself, but also on each element. Therefore, when you have a reference to an element, you can use these methods to search its children without having to traverse the entire document. You can see some simpler examples in this section.
To find all the <p> elements on a page, you can use this syntax:
document.querySelectorAll("p");
To find an element by its unique ID, you can use this syntax:
document.querySelector("#outerDiv");
Put those two lines into your HTML file and try them out. You will explore much more advanced and interesting functionality in Chapter 4. For now, you can use what you’ve seen about finding elements in the DOM to apply that knowledge to adding or modifying the DOM through code.
EXAM TIP
jQuery is probably the most popular library available to date for simplifying and extending the core JavaScript capabilities. Although jQuery isn’t a Microsoft technology, it’s essentially an industry standard and fully supported by Microsoft. As such, web developers today are generally understood to have a grasp of using jQuery interchangeably with core JavaScript.
The exam will expect that you can use jQuery effectively in place of the document object selector methods.