Reputation: 1622
I am trying to get background color of each child element.
var arr = [];
for(var c = 0; c < 5; c++){
var temp = div.children[c].style.backgroundColor;
arr[c] = temp;
}
I can't seem to understand why it's not working because when I used the code below, it worked
div.children[c].style.backgroundColor = "#eee";
Upvotes: 1
Views: 1155
Reputation: 24925
An alternate to avoid custom creating of array.
var div = document.getElementById("text");
var arr = Array.prototype.map.call(div.children, function(el) {
return window.getComputedStyle(el).backgroundColor;
})
console.log(arr)
<div ID="text">
<span style="background-color:rgb(200,20,20)">1</span>
<span style="background-color:rgb(250,150,150)">2</span>
<span style="background-color:rgb(150,100,0)">2</span>
</div>
Upvotes: 2
Reputation: 36609
The
Window.getComputedStyle()
method gives the values of all theCSS
properties of an element after applying the active stylesheets and resolving any basic computation those values may contain.The
HTMLElement.style
property returns a CSSStyleDeclaration object that represents only theelement's inline style attribute
, ignoring any applied style rules.
HTMLElement.style
only works for inline-css
, use getComputedStyle(Element)
to get all the style
object associated with Element
.
Note: I would use Array#push
instead of assigning values at specified index
.
var arr = [];
for (var c = 0; c < 5; c++) {
var temp = getComputedStyle(div.children[c]).backgroundColor;
arr.push(temp);
}
Upvotes: 4