0

I have a cell class

  .cell {
    width:30px;
    height:30px;
  }

In my createCell function:

  var createCell = function(id) {
    var div = document.createElement('div');
    div.id = id;
    div.className = 'cell';
    div.addEventListener('click', function() {
      div.style.background = pickedColor;
    });
    document.getElementById('gridArea').appendChild(div);
  }

as you can see, i have already assigned className to 'cell'. After calling this function, I call

document.getElementById(id).style.width

It returns empty string ""

Why is it so? how can I retrieve the value immediately after assigning the className?

Spencer Wieczorek
  • 21,229
  • 7
  • 44
  • 54
OMGPOP
  • 1,995
  • 8
  • 52
  • 95
  • Rolled back your question, please don't modify the code in the question otherwise an answer which was originally valid will look invalid. If it didn't fix the issue comment on the answer or add the updated code below the question. – Script47 Oct 10 '15 at 00:01
  • 1
    Because `.style` is only for the `styles` directly on that element, styles from a class doesn't count in that case. – Spencer Wieczorek Oct 10 '15 at 00:06
  • 1
    Possible duplicate of [JavaScript get Styles](http://stackoverflow.com/questions/4172871/javascript-get-styles) – CBroe Oct 10 '15 at 00:12

3 Answers3

2

You need to use getComputedStyle to get styles that come from CSS. .style just accesses the style attributes of the DOM element.

width = getComputedStyle(document.getElementById(id)).width;
Barmar
  • 741,623
  • 53
  • 500
  • 612
0

You don't assign the id parameter the the id of the actual element anywhere.

What you need to do is this,

div.id = id

Edit 1

You need to use getComputedStyle.

alert(getComputedStyle(div).width);

The JSFiddle shows how.

http://jsfiddle.net/kvohdnbn/

Script47
  • 14,230
  • 4
  • 45
  • 66
0

If your underlying goal is to access the width of the element, you should use its .offsetWidth property.

style.width will only have a value if one has been set using the style attribute, not via the application of CSS classes.

Try document.getElementById(yourIdHere).offsetWidth

James Henry
  • 844
  • 6
  • 12