Javascript DOM HTML Element children Property change child background

Introduction

Loop through all children of <body> and change their background color to red:

Click the button to change the background color of all child elements of body.

View in separate window

<!DOCTYPE html>
<html>
<body>
<button onclick="myFunction()">Test</button>

<h2>I am a h2 element</h2>

<div>I am a div element</div>
<span>I am a span element</span>

<script>
function myFunction() {//  ww  w .jav a 2s.c o m
  var c = document.body.children;
  var i;
  for (i = 0; i < c.length; i++) {
    c[i].style.backgroundColor = "red";
  }
}
</script>

</body>
</html>



PreviousNext

Related