Javascript examples for DOM:Element getElementsByClassName
Element getElementsByClassName() Method - Change the background color of the second element with class="child" inside of a <div> element:
<!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>