Skip to main content

HTML DOM getElementsByClassName() Method in JAVA SCRIPT

Definition and Usage..
The getElementsByClassName() method returns a collection of all elements in the document with the specified class name, as a NodeList object.
The NodeList object represents a collection of nodes. The nodes can be accessed by index numbers. The index starts at 0.
Tip: You can use the length property of the NodeList object to determine the number of elements with a specified class name, then you can loop through all elements and extract the info you want.
Syntax: document.getElementsByClassName(classname)
CODING:
<!DOCTYPE html>
<html>
<body>
<p class="p">p tag</p>
<p class="p">p tag</p>
<p class="p">p tag</p>
<button onclick="color()">change color</button>
<button id="count" onclick="countElement()">count P tag</button>
<div class="parent">
  <span style="font-size:23pt;color:green;" class="child">JAVA</span>
  <h1 class="child">JAVA SCRIPT</h1>
</ul>
<button onclick="change()">change JAVA</button>

<p><strong>Note:</strong> The getElementsByClassName() method is not supported in Internet Explorer 8 and earlier versions.</p>

<script>
var pTag=document.getElementsByClassName("p");
function color(){
    pTag[2].style.backgroundColor = "red";
}
function countElement() {
document.getElementById("count").innerHTML=pTag.length+" P tag";
}
function change() {
    var div = document.getElementsByClassName("parent")[0];
    div.getElementsByClassName("child")[0].innerHTML = "ERLANG";
}

</script>
</body>
</html>

Comments