'How to select all div from body and not from the header?

I use this javascript code in order to select all DIVs and change their color. I don't want to change color of the DIV in the header. Purpose of this task is to learn HTML5, DOM, Javascript and getElementsByTagName function:

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <title>test</title>
    <div>divv in header</div>
</head>
<body onload="Onload()">
    <div>bla</div>
    <div id="Div1">bla</div>
    <div id="Div2">bla
        <div id="Div4">div in div</div>
    </div>
    <div id="Div3" class="diiiivvv">bla</div>
</body>
</html>

<script type="text/javascript">
    function Onload() {
        var h = document.head;
        var dh = h.getElementsByTagName('div');
        if (dh.length != 0) {
            dh[0].style.backgroundColor = 'red'; //fail
        }            

        var d = document.getElementsByTagName('div');

        for (var i = 0; i < d.length; i++) {
            d[i].style.backgroundColor = 'blue';
        };
    }
</script>


Solution 1:[1]

Where is your problem? You just did it right to select the div in head:

    var h = document.head;
    var dh = h.getElementsByTagName('div');
    // or short:
    var dh = document.head.getElementsByTagName('div');

So why don't you use the same for the body element:

    var db = document.body.getElementsByTagName('div');

The getElementsByTagName() method can be applied on any dom element.

Solution 2:[2]

You may find it best to access the required elements using a CSS selector and appropriate style rule. Here's an example:

<script type="text/javascript">

function applyRule(selectorText, value) {

  // Get the style sheets - note sytleSheets is a live HTMLCollection
  var sheet, sheets = document.styleSheets;

  // Add a style sheet if there isn't one in the document
  if (!sheets.length) {
    sheet = document.createElement('style');
    sheet.type = 'text/css';
    document.getElementsByTagName('head')[0].appendChild(sheet);
  }

  // Get the last style sheet
  sheet = sheets[sheets.length - 1];

  // Add the rule - W3C model
  if (sheet.insertRule) {
    sheet.insertRule(selectorText + ' {' + value + '}', sheet.cssRules.length);

  // IE model
  } else if (sheet.addRule) {
    sheet.addRule(selectorText, value, sheet.rules.length);
  }  
}
</script>

<div>here is a div
<button onclick="applyRule('div','background-color: red')">Change div background colour</button>
</div>

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Bergi
Solution 2 RobG