Element children Property - Loop through all children of <body> and change their background color to red: - Javascript DOM

Javascript examples for DOM:Element children

Description

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

Demo Code

ResultView the demo 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() {//from   w ww . j a v  a  2 s.  c om
    var c = document.body.children;
    var i;
    for (i = 0; i < c.length; i++) {
        c[i].style.backgroundColor = "red";
    }
}
</script>

</body>
</html>

Related Tutorials