phoxd
phoxd

Reputation: 1622

Get style property of each children using loop

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

Answers (2)

Rajesh
Rajesh

Reputation: 24925

An alternate to avoid custom creating of array.

Array.map.call

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

Rayon
Rayon

Reputation: 36609

The Window.getComputedStyle() method gives the values of all the CSS 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 the element'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

Related Questions