somdow
somdow

Reputation: 6318

How to target and affect dom element in js (noobie)

so long story short,

I'm testing something out, a simple rollover and i notice that for example, if i use this

css:
#box{ width:200px; height:200px; background-color:#F00;}

html:
<div id="box" class="boxClass">this is sample text</div>


Js:
var box = document.getElementById("box");

function changeBox(){
    //box.style.backgroundColor = "#1896fa";    
    box.style.backgroundColor = "#1896fa";

}

box.onmouseover = changeBox;

it works, simple as can be. simple mouseover, simple js...simple. Mouse rolls over and changes from red to bue...good, but then when i try to target the same div via

var box = document.getElementsByTagName("div");

or

getElementsByClassName("boxClass");

nothing happens. my ? is why?

reason im asking is because, i have a simple image gallery and wanted to implement gallery wide rollovers but didnt want to write them for EVERY image.

was trying to somehow group them all together via tagName("img") or ClassName("boxClass")

but to no avail. i know older browsers dont support some of these but i looked it up and saw all modern browsers sans Ie are a go. what am i missing?

any tips help direction is appreciated. thanks in advance.

Upvotes: 0

Views: 88

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039588

Contrary to the getElementById function which returns a single element, the getElementsByTagName function returns a NodeList of DOM elements (which is normal as you could have multiple elements with this tag). So if you want to change the background color to all <div> elements in the DOM you will have to first loop through the elements of this collection.

var boxes = document.getElementsByTagName("div");
for (var i = 0; i < boxes.length; i++) {
    boxes[i].style.backgroundColor = "#1896fa"; 
}

Same remark stands true for the getElementsByClassName function.

Upvotes: 2

Related Questions