Beginning DOM Manipulation

on Thu Aug 28 11:23:13 GMT 2008 in Javascript and viewed 13533 times

A beginning perspective into how to use the Document Object Model using Javascript to manipulate page elements on the fly. Covers getElementById, getElementsByTagName, childNodes, firstChild, lastChild, and nodeValue.


The Document Object Model (abbreviated DOM) is a tree-like representation of the HTML in the page. For example:


<p>
Using <em>javascript</em> is fun.
</p>

This page (well, wouldn’t be valid :)), but it has the root element, <p>. Inside <p>, there are three nodes, an element node, then a text node, then another element node. The first text node for <p> has the text “Using ”. Then an element node <em>, which has a text node inside that which contains the text “javascript”. The last text node in the <p> element says ” is fun”.

Now to start with the Javascript. There are two functions you need to know about to access the DOM. They are getElementById and getElementsByTagName. In this tutorial though, we will cover a few different ways to use the DOM, including: getElementById, getElementsByTagName, childNodes, firstChild, lastChild, and nodeValue.

The getElementById function accesses element nodes by their id attribute. Since none of our elements have an id at the moment, we’ll go to getElementsByTagName, which returns an array of all the elements with the tag name you provide. So to start, let’s count the amount of elements in the <p> element.

Example can be found here


<html>
<head><title>Using the DOM</title></head><body>
<p>
Using <em>javascript</em> is fun.
</p>
<script type="text/javascript">
var p = document.getElementsByTagName("p")[0];
var p_children = p.childNodes;
alert(p_children.length);
</script>
</body></html>

Aside from the page elements that I added, there’s everything in between the <script> tags.

The first thing I do is get all of the elements with the tag name of “p.” Notice that I have to have document.getElementsById. Otherwise the javascript interpreter will look for a function named “getElementsById”. Now also notice that I must appened [0] onto the end of the document.getElementsByTagName. This is because that function will return an array, so since we already know there is only one “p” element, we can just access the first one. To cycle all of them, we could have used a for loop:

Example can be found here.


var text = "Hey! " 
var p = document.getElementsByTagName("p");
for ( x = 0; x < p.length; x++ ){
text = text + p[x].firstChild.nodeValue
text = text + p[x].lastChild.nodeValue
}
alert(text)//don't laugh at the output, totally unintentional

This uses another three concepts: firstChild, lastChild, and nodeValue. As you would think, firstChild and lastChild are pretty self-explanatory, fetching the first and last child of the element that was the parent. Then nodeValue returns the value of the node.

Now you could just as easily set the values of the element with nodeValue as well. This time let’s make the text say something totally not true.

Example can be found here.


<html>
<head><title>Using the DOM</title></head><body>
<p>
Using <em>javascript</em> is fun.
</p>
<script type="text/javascript">
var text = "Hey! " 
var p = document.getElementsByTagName("p")[0];
p.lastChild.nodeValue = " is not fun";
</script>
</body></html>

The output of the page will change “Using javascript is fun” to “Using javascript is not fun”. Even though the file says different, the javascript changes the html to say what it wants. Now this is kind of boring, so we can attach it to a function for the last thing to do. And let’s also change <p> to have an id to illustrate documentgetElementsById..

Example can be found here.


<html>
<head><title>Using the DOM</title>
<script type="text/javascript">
function change(){
var p = document.getElementById("paragraph")
p.lastChild.nodeValue = " is not fun." 
}
</script></head><body>
<p id="paragraph">
Using <em>javascript</em> is fun.
</p>
<a href="#" onclick="change()">click me</a>
</body></html>

First thing to notice is that we added an id to the <p> element. IDs are used to define CSS rules as well as used in the DOM. Then there’s the new link. The link has the href value of ”#”, meaning that it won’t go anywhere. Now the onclick value is change(), meaning that the javascript function change() will be invoked.

The next item of interest is that I moved the script block into the head section of the document. This is because you can’t define an element that does not exist yet, so if you put the script block above the paragraph in the body, it would present an error. The easy way to do this is to put the script in the head. This is more useful when you develop more advanced scripts.

The function change() is very simple. It has no arguments, just defines p as the paragraph. Notice that I didn’t need to access any elements, because it returns one object. An id should be unique throughout the document. Then I can just find the last child’s node value and change it to ” is not fun” once the function is executed by clicking the link.

That’s basically all for now. I will put out another article very soon on how to manipulate the DOM with some more advanced techniques.

Also, this javascript does not degrade very gracefully. Using the href=”#” is not a good idea, because if a browser doesn’t have javascript enabled, then the functionality is pointless. Now this was fine for this demonstration, but for more advanced projects, make sure that your website works without javascript enabled.

Part 2 Part 3