1

I am a newbie at javascript and I want change the color of elem2. But this doesn´t work:

    var elem = document.getElementById("test");
    var elem2 = document.getElementById("test2");

    var color = elem.style.backgroundColor;
    elem2.style.backgroundColor = color;

Any ideas? THX

  • I have two: 1) the JS is run before the elements are loaded; 2) the element with ID `test` doesn't have inline `background-color` style. – VisioN May 07 '14 at 14:59
  • 1
    If you set `elem`'s color using a stylesheet (not inline), the you must use [`getComputedStyle`](https://developer.mozilla.org/en-US/docs/Web/API/window.getComputedStyle) – Oriol May 07 '14 at 15:00
  • http://stackoverflow.com/questions/6338217/get-a-css-value-with-javascript – bottens May 07 '14 at 15:01
  • Hi, thank you... with getComputedStyle it works very well and so how I wanted it. Does it mean that my approach above is only working for inline elements? – user3612671 May 07 '14 at 16:31

3 Answers3

1

Try this:

var elem = document.getElementById('test');
var elem2 = document.getElementById('test2');    

var color = window.getComputedStyle(elem).getPropertyValue('background-color');
elem2.style.backgroundColor = color;

Sample JSFiddle

DarkAjax
  • 15,955
  • 11
  • 53
  • 65
0

Basically your code is correct.

If block with id "test" has attribute "style" with backgroundColor, written inline, it should work. It should be something like:

<div id="test" style="background-color: red"> </div>

If you declare background-color it css style your js will not work.

However next one color identification will work in both situations:

var color = window.getComputedStyle(elem).getPropertyValue('background-color');

So try to debug it using web-inspector.

Make sure variable "color" contains needed color - add

console.log(color)

and see result in console.

Also check "elem" and "elem2", maybe you have errors in ids.

QArea
  • 4,955
  • 1
  • 12
  • 22
-1

change this line

var color = elem.style.backgroundColor;

for this

var color = "red"; // or other you want #333
Miktown
  • 89
  • 5