HTML DOM getElementsByTagName() method


The HTML DOM getElementsByTagName() method is used for getting the collection of all the elements in the document having a given tag name. It returns all the given elements as a NodeList object. You can access any element in the returned object using the index number.

The HTMLcollection returned stays sync with the DOM tree without calling the getElementsByTagName() method again and again after removing or adding some elements.

Syntax

Following is the syntax for the getElementsByTagName() method −

element.getElementsByTagName(tagname)

Here, tagname is a mandatory parameter value indicating the child elements tagname that we want to get.

Example

Let us look at an example for the getElementsByTagName() method −

<!DOCTYPE html>
<html>
<head>
<script>
   function changePara() {
      var p = document.getElementsByTagName("P");
      p[0].innerHTML = "This text has been changed";
      p[1].style.color = "red";
      p[1].style.backgroundColor = "yellow";
   }
</script>
</head>
<body>
<h1>getElementsByTagName() example</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>
<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>
<button onclick="changePara()">CHANGE</button>
</body>
</html>

Output

This will produce the following output −

On clicking the CHANGE button −

In the above example −

We have created two paragraphs that have no attributes associated with them −

<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>

<p>Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat</p>

We have then created a button CHANGE that will execute the changePara() on being clicked by the user −

<button onclick="changePara()">CHANGE</button>

The changePara() method gets both the <p> elements as nodeListObject using the getElementsByTagName() method upon the document object and assigns it to variable p. Using the index numbers we change the text for the first paragraph and apply some styling to the second paragraph −

function changePara() {
   var p = document.getElementsByClassName("PARA1");
   p[0].innerHTML = "This text has been changed";
   p[1].style.color = "red";
   p[1].style.backgroundColor = "yellow";
}
raja
Published on 09-Aug-2019 11:57:56
Advertisements