Accessing Element Nodes

Contact Us or call 1-877-932-8228
Accessing Element Nodes

Accessing Element Nodes

innerHTML

Most HTML elements have an innerHTML property, which can be used to access and modify the HTML within that element. The innerHTML property wasn't included in any specification until HTML5. However, as it's extremely useful and well supported, we will use it widely throughout this course.

innerHTML Illustration:

Given the code:
<p>I <strong>love</strong> Webucator.</p>
the innerHTML property of the <p> tag would be: "I <strong>love</strong> Webucator."
Tip: you can use the innerHTML property to either get the element's inner HTML value (as shown above) or you can use it to set the element's inner HTML value. More on this later in the lesson.

JavaScript provides several different ways to access elements on the page. Let's have a look.

The document.getElementById() Method

Chances are you have already seen the document.getElementById() method, which returns the first element with the given id (there shouldn't be more than one on the page!) or null if none is found. The following example illustrates how getElementById() works:

Code Sample:

HTMLDOM/Demos/getElementById.html
---- C O D E   O M I T T E D ----

function show() {
	var elem = document.getElementById("BeatleList");
	alert(elem.innerHTML);
}
---- C O D E   O M I T T E D ----

<body onload="show();">
<h1>Rockbands</h1>
<h2>Beatles</h2>
<ol id="BeatleList">
	<li>Paul</li>
	<li>John</li>
	<li>George</li>
	<li>Ringo</li>
</ol>
<h2>Rolling Stones</h2>
<ol id="StonesList">
	<li>Mick</li>
	<li>Keith</li>
	<li>Charlie</li>
	<li>Bill</li>
</ol>
</body>
</html>

When this page loads, the following alert box will pop up:

The element.getElementsByTagName() Method

The elementgetElementsByTagName() method of an element node retrieves all descendant (children, grandchildren, etc.) elements of the specified tag name and stores them in a NodeList, which is similar, but not exactly the same as an array of nodes. The following example illustrates how elementgetElementsByTagName() works:

Code Sample:

HTMLDOM/Demos/getElementsByTagName.html
---- C O D E   O M I T T E D ----

function getElements()
{
	var elems = document.getElementsByTagName("li");
	var msg="";
	for (var i=0; i < elems.length; i++)
	{
		msg += elems[i].innerHTML + "\n";
	}
	alert(msg);
}
</script>
<title>getElementsByTagName()</title>
</head>

<body onload="getElements();">
<h1>Rockbands</h1>
<h2>Beatles</h2>
<ol>
	<li>Paul</li>
	<li>John</li>
	<li>George</li>
	<li>Ringo</li>
</ol>
<h2>Rolling Stones</h2>
<ol>
	<li>Mick</li>
	<li>Keith</li>
	<li>Charlie</li>
	<li>Bill</li>
</ol>
</body>
</html>

When this page loads, the following alert box will pop up:

The document.getElementsByClassName() Method

The document.getElementsByClassName() method is well supported by browsers (with one major exception) and is officially part of HTML5. Applicable to all elements that can have descendant elements, document.getElementsByClassName() is used to retrieve all the descendant (children, grandchildren, etc.) elements of a specific class. For example, the following code would return a node list containing all elements of the "warning" class:

var warnings = document.getElementsByClassName("warning");

Unfortunately, document.getElementsByClassName() is not supported by IE until version 9, but we can use this helper function for backward compatibility:

function getElementsByClassName(node,classSearch) {
	if (node.getElementsByClassName) {
		//returns nodeList
		return node.getElementsByClassName(classSearch);
	} else {
		//returns array
		var classElements = [];
		var elems = node.getElementsByTagName("*");
		var pattern = new RegExp("(^|\\s)" + classSearch + "(\\s|$)");
		for (var i in elems) {
			if (pattern.test(elems[i].className) ) {
				classElements.push(elems[i]);
			}
		}
		return classElements;
	}
}

This function, included in ClassFiles/lib.js, will use the browser's native document.getElementsByClassName() if it exists. Otherwise, it traverses the nodeTree finding elements with the specified class name and returns an array of matched elements.

The document.querySelectorAll() Method

The document.querySelectorAll() method gives you access to elements using the CSS selector syntax. For example, the following code would return a node list containing all list items that are direct children of ol tags:

var orderedListItems = document.querySelectorAll("ol>li");

The document.querySelector() Method

The document.querySelector() method is the same as document.querySelectorAll() but rather than returning a node list, it returns only the first element found. The following two lines of code would both return the first list item found in an ol tag:

var firstOrderedListItem = document.querySelectorAll("ol>li")[0];
var firstOrderedListItem = document.querySelector("ol>li");

The querySelectorAll() and querySelector() methods are not supported until version 8 of Internet Explorer and version 3.5 of Firefox and they are, unfortunately, difficult to reproduce. Note that popular JavaScript libraries such as YUI and jQuery implement cross-browser CSS selector utilities.

Accessing Element and Text Nodes Hierarchically

There are several node methods and properties that provide access to other nodes based on their hierarchical relationship. The most common and best supported of these are shown in the table below.

Properties for Accessing Element Nodes
Property Description
childNodes[] A nodeList containing all of a node's child nodes.
firstChild A reference to a node's first child node.
lastChild A reference to a node's last child node
nextSibling A reference to the next node at the same level in the document tree.
parentNode A reference to a node's parent node.
previousSibling A reference to the previous node at the same level in the document tree.

The this Object

The this keyword provides access to the current object. It references the object in which it appears.

The following example shows a page (HTMLDOM/Demos/Hierarchy.html) on which a mouse click on any element will display a message giving information about that element's position in the object hierarchy.

When you click on the middle list item, for example, you get the following message:

This shows that the list item's parent is an unordered list (UL), its first child is a text node ("List Item 2"), its last child is the same as it only has one child, its next and previous siblings are both text nodes, and it has only one child node (the text node). Again, this message was generated in Firefox, but would be the same in other modern browsers. However, as we'll see later, the result will be slightly different in Internet Explorer 8 and earlier.

Next