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.

We use the following HTML page to demonstrate the most important methods.   
<!DOCTYPE html>
<html>
<head>
  <script>
    function show() {
      "use strict";
      // ...
    }
  </script>
  <style>
    .head_2 {
      display: flex;
      justify-content: center;
    }
    .text {
      padding-left: 1em;
      font-size: 1.4em;
    }
    .button {
      height:1.4em;
      width: 4em;
      margin-top: 1em;
      font-size: 1.2em;
      background-color: Aqua;
    }
  </style>
</head>

<body>
  <h1>An HTML header</h1>

  <h2 class="head_2">An HTML sub-header</h2>
  <div id="div_1">
    <p id="p1" class="text">Paragraph 1</p>
    <p id="p2" class="text">Paragraph 2</p>
    <p id="p3" class="text">Paragraph 3</p>
  </div>

  <div id="div_2">
    <h2>Another HTML sub-header</h2>
    <div id="div_3">
      <p>Another paragraph 1</p>
      <p>Another paragraph 2</p>
      <p>Another paragraph 3</p>
    </div>
  </div>

  <button class="button" onclick="show()">Go</button>

</body>
</html>

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

Using ID

edit

An easy-to-use, fast, and exact method to locate an individual element is to mark the element with the id property in the HTML, e.g., <p id="p2">, and use this id as the parameter to getElementById(). The following code snippet will locate the element and displays its content.

function show() {
  "use strict";
  const elem = document.getElementById("p2");
  alert(elem.innerHTML);
}

The getElementById method returns one single element (the first with this id if the id 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.

function show() {
  "use strict";
  const elem = document.getElementById("div_3");
  alert(elem.innerHTML);
}
// expected output:
// <p>Another paragraph 1</p>
// <p>Another paragraph 2</p>
// <p>Another paragraph 3</p>

Using tag name

edit

Another way to find elements on an HTML page is the getElementsByTagName 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.

function show() {
  "use strict";

  // if you want to search in the complete document, you must specify 'document'
  let elemArray = document.getElementsByTagName("div");
  // loop over all array elements
  for (let i = 0; i < elemArray.length; i++) {
    alert(elemArray[i].innerHTML);
  }

  alert("Part 2");

  // if you want to search only a sub-tree, you must previously locate
  // the root of this sub-tree
  const elem = document.getElementById("div_2");
  elemArray = elem.getElementsByTagName("div");
  for (let i = 0; i < elemArray.length; i++) {
    alert(elemArray[i].innerHTML);
  }
}

Using class name

edit

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 div. Please note, that the other paragraphs are not retrieved.

function show() {
  "use strict";

  let elemArray = document.getElementsByClassName("text");
  // loop over all array elements
  for (let i = 0; i < elemArray.length; i++) {
    alert(elemArray[i].innerHTML);
  }
}

Using a query selector

edit

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 querySelector method. If you want to retrieve all matching elements, use querySelectorAll.

function show() {
  "use strict";

  // '#' locates via ID, '.' locates via CSS class
  let elemArray = document.querySelectorAll("h1, #p2, .head_2");
  // loop over all array elements
  for (let i = 0; i < elemArray.length; i++) {
    alert(elemArray[i].innerHTML);
  }
}
edit

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.

function show() {
  "use strict";

  // start at 'div_2'
  const elem_1 = document.getElementById("div_2");
  // use this element as the new root for further selections
  const elemArray = elem_1.getElementsByTagName("h2");
  for (let i = 0; i < elemArray.length; i++) {
    alert(elemArray[i].innerHTML);
  }
  // only the child-'h2' is selected! The first 'h2' is ignored.
}

See also

edit

Exercises

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