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
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With