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?

3
  • 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. Commented Oct 10, 2015 at 0:01
  • 1
    Because .style is only for the styles directly on that element, styles from a class doesn't count in that case. Commented Oct 10, 2015 at 0:06
  • 1
    Possible duplicate of JavaScript get Styles Commented Oct 10, 2015 at 0:12

3 Answers 3

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;
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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/

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.