PhoxKiD PhoxKiD - 2 months ago 5
HTML Question

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";

Answer

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);
}
Comments