JavaScript/Finding elements

To work with nodes of the DOM tree, you need to locate them directly or navigate to them beginning at a starting point. DOM's Document interface serves as an entry point into the web page's content. It offers a rich set of properties and methods to reach particular nodes. The methods return single nodes or an array of nodes.

Clicking on the  invokes the function. The examples should be included there.

Using ID
An easy-to-use, fast, and exact method to locate an individual element is to mark the element with the  property in the HTML, e.g., , and use this   as the parameter to. The following code snippet will locate the element and displays its content.

The  method returns one single element (the first with this   if the   is not unique).

That is also true if the element is not a text node but a node with child nodes. The return value is a single element with all its child elements included.

Using tag name
Another way to find elements on an HTML page is the  method. It accepts a tag name, e.g., 'h1', 'div', or 'p', and returns all such elements in an array.

Here, we use the method to retrieve an array of all 'div' elements.

Using class name
Next, elements can be located by an associated CSS class selector. Class selectors can have a complex syntax. Here, we use only the simple form of class names.

The example retrieves all elements that use the CSS class text - what is done by the 3 paragraphs of the first. Please note, that the other paragraphs are not retrieved.

Using a query selector
The shown locating methods use specialized semantics to locate elements. But there is also a general method that combines all of that - plus more.

Query selectors use a complex syntax consisting of HTML element ids, HTML element names, HTML attributes, CSS classes, positions, and more. They locate single elements or a list of elements. To retrieve the first element which satisfies the selector, use the  method. If you want to retrieve all matching elements, use.

Navigating the DOM tree
You can navigate in the DOM tree in the direction from the root to the leaves. This is done by locating an element and using this node as the new root for the following navigation steps.

Exercises

 * ... are available on another page (click here).