HTML DOM getElementsByClassName() method


The HTML DOM getElementsByClassName() method is used for getting the collection of all the elements in the document having a given class name. It returns all the given elements as a NodeList object. You can access any element in the returned object using the index number. This method can be called on any individual element to have its descendant child elements having the given class name.

Syntax

Following is the syntax for the getElementsByClassName() method −

document.getElementsByClassName(classname)

Here, the classname is of type string indicating the class name of element you want to access. Multiple class names can also be searched by separating them with space.

Example

Let us look at an example of the getElementsByClassName() method −

<!DOCTYPE html>
<html>
<head>
<script>
   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";
   }
</script>
</head>
<body>
<h1>getElementsByClassName() example</h1>
<p class="PARA1">Lorem ipsum dolor sit amet, consectetur adipiscing elit,
sed do eiusmod tempor incididunt ut labore et dolore magna aliqua</p>
<p class="PARA1"> 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 classname=”PARA1” associated with them.

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

<p class="PARA1"> 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 getElementsByClassName() 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:50:32
Advertisements