Get HTML elements by TagName

In javascript, getElementsByTagName() method is useful to access the HTML elements using the tag name. This method is the same as the getElementsByName method. Here, we are accessing the elements using the tag name instead of using the name of the element.

Syntax:

document.getElementsByTagName(Tag_name);

Parameter:

It takes a single parameter which is the tag name.

Return value:

It returns the collection of elements that includes the tag which passed as a parameter.

Example: This example demonstrates the use of the getElementsByTagName method. It prints every element with a particular tag into the console. 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>
    <!-- Multiple html element with h1 tag -->
    <h1>w3wiki sample 1</h1>
    <h1>w3wiki sample 2</h1>
    <h1>w3wiki sample 3</h1>
 
    <p>DOM getElementsByTagName() Method</p>
 
    <script>
        // Accessing the element by
        // getElementsByTagName method
        let temp = document.getElementsByTagName("h1");
        console.log(temp[0]);
        console.log(temp[1]);
        console.log(temp[2]);
    </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

...