How to find elements in DOM in JavaScript? [SOLVED]


JavaScript

Introduction

When working with JavaScript, you often need to find the value of an element in the DOM (Document Object Model). The DOM is a tree-like structure that represents the HTML document. Each element in the DOM has a unique ID, which can be used to find the element in JavaScript. This article will discuss ways to find elements in the DOM.

 

Different methods in JavaScript to find Elements in the DOM

There are two ways to find an element in the DOM:

  1. Use the document.getElementById() method.
  2. Use the document.querySelector() method.
  3. Use the document.getElementsbyTagName
  4. Use the document.getElementsbyClassName method

 

Method-1: Use the document.getElementById() method

The document.getElementById() method is the most common way to find an element in the DOM. This method returns the element with the specified ID. For example, if you have an element with an ID of "my-element", you can use the following code to find it:

let element = document.getElementById("my-element");

Once you have found an element in the DOM, you can use the element.innerText property to get its value. For example, if you have an input element with an ID of "my-input", you can use the following code to get its value:

let inputValue = document.getElementById("my-input").in;

You can also use the element.innerHTML property to get the HTML contents of an element. For example, if you have a div element with an ID of "my-div", you can use the following code to get its HTML contents:

let divContents = document.getElementById("my-div").innerHTML;

Let’s illustrate the getElementById() method across a simple HTML page. In the code, we will find the elements with certain identifiers - my-element and my-div - and access their code using the innerText and innerHTML properties.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <p id="my-element">This is a paragraph element</p>
        <input type="text" id="my-input" />
        <div id="my-div">
            Some div (division)
            <p>This is a paragraph element within a div element</p>
        </div>
        <script>
            let element = document.getElementById("my-element");
            let divContents = document.getElementById("my-div").innerHTML;

            console.log(element.innerText);
            console.log(divContents);
        </script>
    </body>
</html>

Output

This is a paragraph element

						Some div (division)
            <p>This is a paragraph element within a div element</p>

To access the output when you render the HTML page in a browser, check the developer console by pressing (Ctrl + Shift + I/ Command + Shift + I) and access the Console tab.

 

Method-2: Use the document.querySelector() method

If you want to find an element with a specific class, you can use the document.querySelector() method. This method returns the first element that matches the specified CSS selector. For example, if you want to find an element with the class "my-class", you can use the following code:

let element = document.querySelector(".my-class");

You can also use the document.querySelector() method to find an element by its ID. For example, if you have an element with an ID of "my-element", you can use the following code to find it:

let element = document.querySelector("#my-element");

Let’s illustrate the querySelector() method across a simple HTML page. In the code, we will find the elements with the identifier - my-element - and the class - my-class - and access their code using the innerText and innerHTML properties.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <h2 id="my-element">My Element Heading</h2>
        <p class="my-class">This is the paragraph with the "my-class" class.</p>
        <script>
            let elementCL = document.querySelector(".my-class");
            let elementID = document.querySelector("#my-element");

            console.log(elementCL.innerText);
            console.log(elementID.innerHTML);
        </script>
    </body>
</html>

Output

This is the paragraph with the "my-class" class.
My Element Heading

Method-3: Use the document.getElementsbyTagName and document.getElementsbyClassName method

Aside from the two methods we have mentioned, we can make use of the getElementsbyTagName method to search for elements with a particular HTML tag (say p or b tags) and the getElementsbyClassName method to search for elements with a particular class name (say main or side class). As both methods returns an array-like object (based on the HTMLCollection, you can iterate over their return value or access their content via index.

Let’s illustrate how to make use of both methods via a simple HTML page.

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge" />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
        <title>Document</title>
    </head>
    <body>
        <h2 id="my-element">My Element Heading</h2>
        <p class="my-class">This is the paragraph with the "my-class" class.</p>
        <p>This paragraph doesn't have a class or identifier.</p>
        <script>
            let myClass = document.getElementsByClassName("my-class");
            let paragraph = document.getElementsByTagName("p");

            console.log(myClass[0]);
            console.log(paragraph[1]);
        </script>
    </body>
</html>

Output

<p class="my-class">This is the paragraph with the "my-class" class.</p>
<p>This paragraph doesn't have a class or identifier.</p>

The output shows HTML values (which are based on the HTMLCollection).

 

Summary

To be able to find elements within the DOM, you can make use of the document.getElementById(), document.querySelector(), document.getElementsbyTagName and document.getElementsbyClassName methods. After which, the value and innerHTML properties can be obtained to get the content or HTML value. The DOM is a tree system that can be easily accessible via the JavaScript language as long as you know the right method to use.

 

References

Document.querySelector() - Web APIs | MDN (mozilla.org)
Document.getElementById() - Web APIs | MDN (mozilla.org)
Document.getElementsByClassName() - Web APIs | MDN (mozilla.org)
Element.getElementsByTagName() - Web APIs | MDN (mozilla.org)

 

Olorunfemi Akinlua

Olorunfemi Akinlua

He is boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs user-friendly interfaces to enhance digital experiences across various domains. You can connect with him on his LinkedIn profile.

Can't find what you're searching for? Let us assist you.

Enter your query below, and we'll provide instant results tailored to your needs.

If my articles on GoLinuxCloud has helped you, kindly consider buying me a coffee as a token of appreciation.

Buy GoLinuxCloud a Coffee

For any other feedbacks or questions you can send mail to admin@golinuxcloud.com

Thank You for your support!!

Leave a Comment