Skip to content

JavaScript get element by tag Method | Simple Example code

  • by

Use getElementsByTagName() method to get the element by tag in JavaScript. Tag name are in HTML h1, p, div, etc.

The Element.getElementsByTagName() method returns a live HTML Collection of elements with the given tag name.

Example of JavaScript get element by tag

Here is HTML example code to get all elements in the document with the specified “h4” tag name:

<!DOCTYPE html>
<html>
<body>

    <h4>An p Tag </h4>


    <button onclick="myFunction()">Try it</button>

    <p id="demo"></p>

    <script>
        function myFunction() {
            var x = document.getElementsByTagName("h4");
            document.getElementById("demo").innerHTML = x[0].innerHTML;
        }
    </script>

</body>
</html>

Output:

JavaScript get element by tag Method

Do comment if you have another example or doubts or suggestions on this topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading