Get HTML element by Id

Generally, most developers use unique ids in the whole HTML document. The user has to add the id to the particular HTML element before accessing the HTML element with the id. Users can use getElementById() method to access the HTML element using the id. If any element doesn’t exist with the passed id into the getElementById method, it returns the null value.

Syntax:

document.getElementById(element_ID);

Parameter:

It takes the ID of the element which the user wants to access.

Return value:

It returns the object with the particular ID. If the element with the particular ID isn’t found, it returns the NULL value.

Example: This example demonstrates the use of the getElementsById method. Also, it prints the inner HTML of a returned object into the console of the browser. Users can open the console in the Chrome web browser by pressing ctrl + shift + I.

HTML




<!DOCTYPE html>
<html lang="en">
<head>
    <title>Document</title>
</head>
 
<body>
    <!-- Heading element with w3wiki id-->
    <h1 id="w3wiki">
        w3wiki
    </h1>
    <p>DOM getElementById() Method</p>
    <script>
        // Accessing the element by getElementById method
        let temp = document.getElementById("w3wiki");
 
        console.log(temp);
        console.log(temp.innerHTML);
    </script>
</body>
</html>


Output:

Different ways to access HTML elements using JavaScript

Sometimes, users need to manipulate the HTML element without changing the code of the HTML. In this scenario, users can use JavaScript to change HTML elements without overwriting them. Before we move ahead to change the HTML element using JavaScript, users should learn to access it from the DOM (Document Object Model). Here, the DOM is the structure of the web page. 

From the DOM, users can access HTML elements in five different ways in JavaScript:

Table of Content

  • Get HTML element by Id
  • Get HTML element by className
  • Get HTML element by Name
  • Get HTML elements by TagName
  • Get HTML elements by CSS Selector

Similar Reads

Get HTML element by Id

Generally, most developers use unique ids in the whole HTML document. The user has to add the id to the particular HTML element before accessing the HTML element with the id. Users can use getElementById() method to access the HTML element using the id. If any element doesn’t exist with the passed id into the getElementById method, it returns the null value....

Get HTML element by className

...

Get HTML element by Name

In javascript, the getElementsByClassName() method is useful to access the HTML elements using the className. The developers can use a single className multiple times in a particular HTML document. When users try to access an element using the className, it returns the collection of all objects that include a particular class....

Get HTML elements by TagName

...

Get HTML elements by CSS Selector

...