7.2 Selecting Nodes in DOM
Nodes in the DOM can be accessed and modified in Javascript.
In order to access nodes in DOM, we need to use the document object. The document object is a built-in Javascript object that represents the HTML document. It comes with a few useful methods and properties for accessing and modifying DOM nodes.
First, create a HTML document in Brackets and name it DOMPractice.html. Add the following code to the page:
<html> <head> <title>DOM Practice</title> </head> <body> <div id = "first">The first div tag</div> <div class = "myclass">The second div tag</div> <div class = "myclass">The third div tag</div> <script type="text/javascript" src="chap7.js"></script> </body> </html>
If you view the HTML page in your browser, you’ll see three lines of text as shown below:
The first div tag
The second div tag
The third div tag
Next, create another file in Brackets and name it chap7.js.
Follow the instructions below to select various elements in our DOMPractice.html page.
7.2.1 getElementById()
The first method that we will be using is the getElementById() method. This method allows us to select an element in Javascript using its id attribute. For instance, the first <div> element in our DOMPractice.html page has id = "first".
To select this element using its id, we write
document.getElementById("first");
We pass in the id name – "first" – to the method. Note that we enclose first in quotation marks (either single or double quotation marks is fine) because getElementById() requires us to pass in the name as a string.
Try adding the line above to chap7.js. Observe what happens.
Nothing happens right?
This is because we have selected the element, but have not made any modifications to it. The getElementById() method simply selects the element and returns the selected element to the caller. Let’s look at how to modify the properties of this selected element.
7.2.2 textContent and innerHTML
Let’s try to change the text enclosed within this element. To do that, we can use either the textContent or the innerHTML property.
Remove the previous line from chap7.js and add the following lines to the file.
var firstDiv = document.getElementById("first"); firstDiv.textContent = "I've changed";
In the code above, we first assign the result of getElementById() to a variable called firstDiv. Next, we use the textContent property of the selected element to change the text enclosed within it.
Try refreshing DOMPractice.html and see what happens. You'll get
I've changed
The second div tag
The third div tag
in the browser. The first line of text has changed to "I've changed".
Quite straightforward right? Let’s move on.
In the previous example, we used the textContent property to change the text content of an element.
Now, what if we want to change the formatting of the text as well? For instance, what if we want the text to be in italics?
To do that, we can use the <em>…</em> HTML tags. Try changing line 2 above to
firstDiv.textContent = "<em>I've changed</em>";
Observe what happens in the browser.
The first line becomes
<em>I've changed</em>
In other words, the <em> and </em> tags are printed on the webpage instead of being recognised as HTML code.
If you want the browser to interpret <em>…</em> as HTML tags, you need to use the innerHTML property.
Change the line to
firstDiv.innerHTML = "<em>I've changed</em>";
You’ll notice that the first line in our HTML page is now in italics.
In other words, the browser now recognizes <em> and </em> as tags and displays the text in italics.
7.2.3 getElementsByClassName()
Next, let’s look at the getElementsByClassName() method. This method selects all the elements that have a certain class name. Hence, the method name is getElementsByClassName (plural) instead of getElementByClassName (singular). The elements selected are returned as an array.
Add the following lines to chap7.js to try this out.
var myclassDiv = document.getElementsByClassName("myclass"); myclassDiv[0].textContent = "MyClass 1"; myclassDiv[1].textContent = "MyClass 2";
Line 1 selects all elements with class = "myclass" as its attribute and stores the result in an array called myclassDiv.
Lines 2 and 3 change the text content of the first and second elements in this array respectively.
If you save chap7.js and refresh DOMPractice.html, you’ll get
I've changed
MyClass 1
MyClass 2
7.2.4 getElementsByTagName()
Next, let’s move on to the getElementsByTagName() method.
Like the name suggests, this method allows us to select elements using tag names. Similar to the getElementsByClassName() method above, this method returns more than one element. Specifically, it returns all the elements that have a certain tag name. The elements are returned as an array.
Add the following lines to chap7.js to try this out.
document.getElementsByTagName("div")[0].textContent = "Tag Name 1"; document.getElementsByTagName("div")[1].textContent = "Tag Name 2"; document.getElementsByTagName("div")[2].textContent = "Tag Name 3";
Here, we did not assign the selected elements to a variable. That’s perfectly fine, though it does make the code a bit more lengthy. If you save chap7.js and refresh DOMPractice.html now, you’ll get
Tag Name 1
Tag Name 2
Tag Name 3
7.2.5 querySelector()/querySelectorAll()
Besides the three methods mentioned above, we also have the querySelector() and querySelectorAll() methods. These two methods allow us to select element(s) in Javascript using the same notation that we use in CSS.
For instance, recall that in CSS, when we want to select a class, we use the . symbol? We do the same here.
The first method only selects the first element while the second method selects all the elements that are applicable.
Try adding the following line to chap7.js.
document.querySelector(".myclass").textContent = "Query Selector CN";
You'll get
Tag Name 1
Query Selector CN
Tag Name 3
The second line in your HTML page changes to "Query Selector CN" because it is the first element that has class = "myclass".
If you want to select all the elements with class = "myclass", you have to use querySelectorAll(). Try adding the following lines to chap7.js.
document.querySelectorAll(".myclass")[0].textContent = "Query Selector All CN 1"; document.querySelectorAll(".myclass")[1].textContent = "Query Selector All CN 2";
You’ll get the following output:
Tag Name 1
Query Selector All CN 1
Query Selector All CN 2
You can also use querySelector() or querySelectorAll() to select elements using their tag names or id attributes. For instance, to select by tag names, we write
document.querySelector("div").textContent = "Query Selector TN"; document.querySelectorAll("div")[2].textContent = "Query Selector All TN";
You'll get the following output:
Query Selector TN
Query Selector All CN 1
Query Selector All TN
Finally, to select by id, you can write
document.querySelector("#first").textContent = "Query Selector ID";
You'll get
Query Selector ID
Query Selector All CN 1
Query Selector All TN
Alternatively, you can also write
document.querySelectorAll("#first")[0].textContent = "Query Selector All ID";
You'll get
Query Selector All ID
Query Selector All CN 1
Query Selector All TN
In the last example above, even though there is only one element with id = "first", we still have to use index 0 to access the element when we use querySelectorAll().