BlogsDope image BlogsDope

Different Ways to Get an HTML Element in JavaScript

June 18, 2020 HTML JAVASCRIPT 14967

We often want to manipulate HTML elements without explicitly having to overwrite the content or change the styling. JavaScript can be used to dynamically update the HTML page. The first step in this regard is to access the HTML element we want to modify. There are multiple ways, for example, we can access a unique element, a group of elements with the same class, etc. Let’s go through them one by one.

Accessing Elements by Id


Elements with a unique id can be accessed by document.getElementById(“idname”). This is the easiest way as it only returns a single element having that id and null if no element is found with that id. In the following example, a paragraph tag is retrieved having the id “description”.

<!DOCTYPE html>

<html>
  <head>
    <title>Get HTML Elements</title>
  </head>

  <body>
    <h1>Get HTML Elements through JavaScript</h1>

    <p id="description">sample text to get elements by id</p>

    <script type="text/javascript">
      description = document.getElementById("description");

      console.log(description);

      console.log(description.innerHTML);
    </script>
  </body>
</html>

The elements are stored in the “description” variable. The “description.innerHTML” retrieves the content. i.e.

<p id="description"> sample text to get elements by id </p>
sample text to get elements by id

If we have more than one elements with the same id, document.getElementById() will only return the first element having that id. Note that this is not encouraged as only one element is supposed to have a single id.

Accessing elements by the Class Name


HTML elements can be grouped by assigning the same class names to the elements. We can get these elements using document.getElementsByClassName(“classname”). It returns an HTML Collection (an array like objects of elements) ordered in the same way as they are in the HTML document. Consider the following example.

<!DOCTYPE html>

<html>
  <head>
    <title>Get HTML Elements</title>
  </head>

  <body>
    <h1>Get HTML Elements through JavaScript</h1>

    <p class="description">sample paragraph 1</p>

    <p class="description">sample paragraph 2</p>

    <p class="description">sample paragraph 3</p>

    <p>sample paragraph 4</p>

    <script type="text/javascript">
      descriptions = document.getElementsByClassName("description");

      console.log(descriptions);

      for (i = 0; i < descriptions.length; i++) {
        console.log(descriptions[i]);
      }
    </script>
  </body>
</html>

The elements are stored in the “descriptions” variable. It looks like this.

1. HTMLCollection(3) [p.description, p.description, p.description]
0: p.description
1: p.description
2: p.description
length: 3
__proto__: HTMLCollection

As you can see in the code above, the individual elements can be accessed by indices like arrays. The output of the for loop is given below.

<p class="description"> sample paragraph 1</p>
<p class="description"> sample paragraph 2</p>
<p class="description"> sample paragraph 3</p>

If elements contain more than one classes, they can be accessed by space separated names of classes. i.e.

<!DOCTYPE html>

<html>
  <head>
    <title>Get HTML Elements</title>
  </head>

  <body>
    <h1>Get HTML Elements through JavaScript</h1>

    <p class="description first">sample paragraph 1</p>

    <p class="description">sample paragraph 2</p>

    <p class="description">sample paragraph 3</p>

    <p>sample paragraph 4</p>

    <script type="text/javascript">
      descriptions = document.getElementsByClassName("description first");

      console.log(descriptions);

      for (i = 0; i < descriptions.length; i++) {
        console.log(descriptions[i]);
      }
    </script>
  </body>
</html>

The above code returns an element having classes “description” and “first”.

1. HTMLCollection [p.description.first]
0: p.description.first
length: 1
__proto__: HTMLCollection

<p class="description first"> sample paragraph 1</p>

This method returns an HTML collection of length 0 if no element exists with the given class name(s).

Accessing Elements by the Tag Name


We can also access elements by its tag name using document.getElementsByTagName(“tagname”). It also returns an HTML collection containing the found elements. The following example obtains all the <p> elements.

<!DOCTYPE html>

<html>
  <head>
    <title>Get HTML Elements</title>
  </head>

  <body>
    <h1>Get HTML Elements through JavaScript</h1>

    <p class="description first">sample paragraph 1</p>

    <p class="description">sample paragraph 2</p>

    <p class="description">sample paragraph 3</p>

    <p>sample paragraph 4</p>

    <script type="text/javascript">
      paragraphs = document.getElementsByTagName("p");

      console.log(paragraphs);

      for (i = 0; i < paragraphs.length; i++) {
        console.log(paragraphs[i]);
      }
    </script>
  </body>
</html>

Output

HTMLCollection(4) [p.description, p.description, p.description, p]
0: p.description
1: p.description
2: p.description
3: p
length: 4
__proto__: HTMLCollection

<p class="description"> sample paragraph 1</p>
<p class="description"> sample paragraph 2</p>
<p class="description"> sample paragraph 3</p>
<p> sample paragraph 4</p>

Accessing Elements by CSS selectors


The HTML elements can also be selected using CSS selectors. Two methods exists for this purpose, document.querySelector(selectors) and document.querySelectorAll(selectors). The querySelector() method returns only the first element matching the given selectors, while the querySelectorAll() returns all the elements. The main advantage is that it is very flexible, and you can pass any CSS selector or a chain of them to access elements. Moreover, it can allow you to access elements using id, class, or tag at the same time i.e. you do not have to use separate methods for it.

The following code accesses the first element having the class “group1”.

<!DOCTYPE html>

<html>
  <head>
    <title>Get HTML Elements</title>
  </head>

  <body>
    <h1>Get HTML Elements through JavaScript</h1>

    <p class="group1">sample paragraph 1</p>

    <p class="group1" id="sample2">sample paragraph 2</p>

    <p class="group2">sample paragraph 3</p>

    <p class="group2">sample paragraph 4</p>

    <script type="text/javascript">
      result = document.querySelector(".group1");

      console.log(result);
    </script>
  </body>
</html>

Output

<p class="group1"> sample paragraph 1</p>

Before going further let’s see some ways to access elements using CSS selectors.

  • Put a dot in front of the class name to access elements by the class i.e. “.classname”.
  • Put a # sign in front of the id name to access an element by the id i.e. “#idname”.
  • Tags can be accessed by just writing the tag name i.e. “p”.

For more details visit CSS Selectors.

The following code accesses all the elements having the class “group1”.

<!DOCTYPE html>

<html>
  <head>
    <title>Get HTML Elements</title>
  </head>

  <body>
    <h1>Get HTML Elements through JavaScript</h1>

    <p class="group1">sample paragraph 1</p>

    <p class="group1" id="sample2">sample paragraph 2</p>

    <p class="group2">sample paragraph 3</p>

    <p class="group2">sample paragraph 4</p>

    <script type="text/javascript">
      result = document.querySelectorAll(".group1");

      console.log(result);

      result.forEach((res) => console.log(res));
    </script>
  </body>
</html>

Output

NodeList(2) [p.group1, p#sample2.group1]
0: p.group1
1: p#sample2.group1
length: 2
__proto__: NodeList

<p class="group1"> sample paragraph 1</p>
<p class="group1" id="sample2"> sample paragraph 2</p>

querySelectorAll() returns a non-live or static NodeList meaning that any modification in the DOM does not affect the collection. It looks like an array, but it is not. It contains all the elements matching the given selectors or an empty NodeList if no matching elements are found.

Consider the following example

<!DOCTYPE html>

<html>
  <head>
    <title>Get HTML Elements</title>
  </head>

  <body>
    <h1>Get HTML Elements through JavaScript</h1>

    <p class="group1">sample paragraph 1</p>

    <p class="group1" id="sample2">sample paragraph 2</p>

    <p class="group2">sample paragraph 3</p>

    <p class="group2">sample paragraph 4</p>

    <script type="text/javascript">
      result = document.querySelectorAll("p.group1#sample2");

      console.log(result);

      result.forEach((res) => console.log(res));
    </script>
  </body>
</html>

Output

NodeList [p#sample2.group1]
0: p#sample2.group1
length: 1
__proto__: NodeList

<p class="group1" id="sample2"> sample paragraph 2</p>

The above code returns an element with <p> tag having id “sample2” and class “group1”.


Liked the post?
A computer science student having interest in web development. Well versed in Object Oriented Concepts, and its implementation in various projects. Strong grasp of various data structures and algorithms. Excellent problem solving skills.
Editor's Picks
0 COMMENT

Please login to view or add comment(s).