2

There is element in HTML: <div id="block"></div>, and it's property via CSS:

#block { 
    background: red;
 }

If I want to assign in JavaScript to some variable a property from CSS, like this:

var value = document.getElementById('block').style.background // It doesn't work

How can I solve this problem?

Matt
  • 3,079
  • 4
  • 30
  • 36
jl284
  • 61
  • 5
  • you forgot a `d`. Is document not ocument ;) – Alex Char Jun 25 '14 at 14:02
  • 2
    BTW: For color, use `background-color` in CSS and `backgroundColor` in Javascript. – Abhitalks Jun 25 '14 at 14:02
  • 1
    it doesn't work for any CSS properties – jl284 Jun 25 '14 at 14:03
  • 1
    The `style` object only contains *local* styles - those set *directly* on the element. Getting the effective style as cascaded through all style sheets is somewhat of a pain, and differs between (old) IE and other browsers. This is one of the more useful things that a framework can help you with. – Pointy Jun 25 '14 at 14:03
  • @JacobLutin: That is because it is via CSS. See Pointy's comment above and j08691's answer below. – Abhitalks Jun 25 '14 at 14:07

4 Answers4

4

You can use getComputedStyle:

var value = window.getComputedStyle(document.getElementById('block')).getPropertyValue("background-color");
console.log(value);
j08691
  • 204,283
  • 31
  • 260
  • 272
  • 2
    Also see [this question](http://stackoverflow.com/questions/15733365/cross-browser-ie8-getcomputedstyle-with-javascript) for Internet Explorer 8 and below. – Pointy Jun 25 '14 at 14:05
0

You could use single line of jQuery for this :

var value = $("#block").css("background-color");
Kedar.Aitawdekar
  • 2,364
  • 1
  • 23
  • 25
  • How is it in any way related to the question? – Abhitalks Jun 25 '14 at 14:08
  • Whenever we assign background:; to element, it is stored as background-color property of that element. And as per question,JacobLutin wanted to extract the value of property background-color of the div#block and assign it to some variable. And var value = $("#block").css("background-color"); does the required. – Kedar.Aitawdekar Jun 25 '14 at 14:19
  • I meant the question is not tagged jQuery. The question is about not being able to get the property via 'style' property in Javascript. – Abhitalks Jun 25 '14 at 14:24
  • Ok, I got it. Mistakenly did not focused on it. – Kedar.Aitawdekar Jun 25 '14 at 14:30
0

If you can use jQuery on your project I recommend using .css() jquery function

Eg.: Setting css

$('#block').css({background:'black'});

Getting css:

var cssValues = $('#block').css('background'});

See more about this here

Melvinr
  • 514
  • 2
  • 8
-2

You can try this -

var  block = document.getElementById("block");
block.setAttribute("style","background-color: red;");
Boris Stitnicky
  • 12,444
  • 5
  • 57
  • 74
  • I don't need to assign property to element, I need to return it don't changing propery in javascript. – jl284 Jun 25 '14 at 14:11