Element getElementsByClassName() Method - Change background color of the first element with both the "child" and "color" class - Javascript DOM

Javascript examples for DOM:Element getElementsByClassName

Description

Element getElementsByClassName() Method - Change background color of the first element with both the "child" and "color" class

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<style>
div {/*from  ww  w  . j av a 2 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