Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using getElementsByTagName to select all divs

Tags:

javascript

I am working on a project where I can only use JS to manipulate an HTML file. I am wanting to change the background color of all divs within the HTML and I currently have the following.

//Highlight Function

function highlight(e) {
  e.target.style.backgroundColor = "orange";
}

function unhighlight(e) {
  e.target.style.backgroundColor = "green";
}

function init() {
  //Mouseover
  var divs = document.getElementsByTagName("div")[0];
  divs.addEventListener('mouseover', highlight, false);
  divs.addEventListener('mouseout', unhighlight, false);
}
window.addEventListener("load", init, false);

The HTML looks like this

<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>

Obviously the current code only changes one of the divs, how do get it to select all of the divs by only manipulating the JS

like image 212
npgiant Avatar asked Apr 04 '13 01:04

npgiant


2 Answers

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

function highlight() {
    this.style.backgroundColor = "orange";
}

function unhighlight() {
    this.style.backgroundColor = "green";
}

function init() {
    for (var i = 0; i < elm.length; i++) {
        if (window.addEventListener) { //Firefox, Chrome, Safari, IE 10
            elm[i].addEventListener('mouseover', highlight, false);
            elm[i].addEventListener('mouseout', unhighlight, false);
        } else if (window.attachEvent) { //IE < 9
            elm[i].attachEvent('onmouseover', highlight);
            elm[i].attachEvent('onmouseout', unhighlight);
        }
    }
}

    if (window.addEventListener) { //when document is loaded initiate init
        document.addEventListener("DOMContentLoaded", init, false);
    } else if (window.attachEvent) {
        document.attachEvent("onDOMContentLoaded", init);
    }

please note that addEventListener is not supported in IE < 9 you have to use attachEvent instead

DEMO

like image 71
razz Avatar answered Sep 20 '22 16:09

razz


You can't use .addEventLister() like that - it has to be called element by element.

for (var i = 0; i < divs.length; ++i)
  divs[i].addEventListener(...);

Alternatively, you could add a single event listener to the <body> element and catch events that bubble up from <div> elements.

like image 26
Pointy Avatar answered Sep 17 '22 16:09

Pointy