Element getElementsByClassName() Method - Javascript DOM

Javascript examples for DOM:Element getElementsByClassName

Description

The getElementsByClassName() method returns child elements by class name as a NodeList object.

Parameter Values

Parameter Type Description
classname String Required.

To search for multiple class names, separate them with spaces, like "child test".

Technical Details

Return Value:

A NodeList object, representing a collection of child elements with the specified class name.

The following code shows how to Change the text of the first list item with class="child" (index 0) in a list with class="example":

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {/*from   w w  w .j  a v  a2 s.c om*/
    border: 1px solid black;
    margin: 5px;
}
</style>
</head>
<body>

<div class="example">
  <p class="child">P0</p>
</div>

<div class="example">
  <p class="child color">P1</p>
  <p class="child color">P2</p>
</div>

<div class="example">
  <p class="child color">P3</p>
  <p class="child color">P4</p>
</div>

<button onclick="myFunction()">Test</button>

<script>
function myFunction() {
    var x = document.getElementsByClassName("example")[1];
    x.getElementsByClassName("child color")[0].style.backgroundColor = "red";
}
</script>

</body>
</html>

Related Tutorials