Element getElementsByClassName() Method - Change the background color of the second element with class="child" inside of a <div> element: - Javascript DOM

Javascript examples for DOM:Element getElementsByClassName

Description

Element getElementsByClassName() Method - Change the background color of the second element with class="child" inside of a <div> element:

Demo Code

ResultView the demo in separate window

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

<div id="myDIV">
  <p class="child">First p element with class="child" in a div (index 0).</p>
  <p class="child">Second p element with class="child" in a div (index 1).</p>
  <p class="child">Third p element with class="child" in a div (index 2).</p>
</div>

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

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

</body>
</html>

Related Tutorials