Selecting Element Nodes

The document object has 3 methods that search the DOM for elements elements that meet the search criteria.

For examples in this section, suppose the web page contains an <h1> element with its id attribute set to “foo” and the class attribute set to “bar” as shown below.

<h1 id=”foo” class="bar">This is foo</h1>

getElementById()

The getElementById(id) function takes a string as an argument returns the element node that has its id property set to the string, otherwise it returns null.

var elm = document.getElementById(“foo”);

getElementsByClassName()

The getElementsByClassName(class) method takes a string of class names (separated by spaces) as an argument and returns a HTMLCollection object of element nodes that have the classes listed in the string included in their class attribute.

var list = document.getElementsByClassName("bar"); 
console.log(list[0].firstChild.nodeValue);    // "This is foo"

The getElementsByClassName() method can be called on any element node.  The method searches the subtree starting at the element node on which the method is called.

var elms = document.body.getElementsByClassName("bar");

getElementsByTagName()

The getElementsByTagName(tag) function takes a string as an argument and returns a HTMLCollection object containing all of the nodes having that a nodeName equal to the string.

We can get a list of all the h1 elements using getElementByTagName() and then search the list using indexing or the HTMLCollection methods.

var headings = document.getElementsByTagName("h1");
console.log(headings[0].firstChild.nodeValue);  // "This is foo"

We can call getElementsByTagName() on any element node.  When called, the method searches the DOM starting at the node on which the method was called (including that node).

var headings = document.body.getElementsByTagName("h1");

To get all of the element nodes in the document in the order in which they appear in the tree (using a depth first search) we pass “*” to the getElementsByTagName() method.

var allElms = document.body.gtElementsByTagName(“*”);

Element.querySelector()

The querySelector(selector) method takes a string containing a valid CSS selector as an argument and returns the first element in the calling element’s subtree that matches the selector.

var container = document.getElementById("container"); 
var boxDiv = container.querySelector(".box");