0

Normally when you have a div created in html. You can check its width with offsetWidth or style.width (if declared). However if the innerHTML is changed such that the width of the div is also change, neither of those functions work (not sure, but they haven't in my cases).

some code:

var div = document.createElement("div");
div.innerHtml = "asdfasdfasdfasdfsdfasdfasdfad";
alert(div.style.width); // this is nothing
alert(div.offsetWidth); // this is 0

How do you get the width of the div above?

1
  • perhaps you'd find dojox/html/metrics useful Commented Apr 9, 2012 at 2:26

2 Answers 2

3

I realize this is an old question, but for the many people landing here from google I'll provide it.

This is the way to do it in dojo 1.7+. With the geometry module you can get and set the width of the content (not including padding or border). This ignores box-sizing.

require(['dojo/dom-geometry'], function(domGeom) {
    var myDivNode = dojo.query('div')[0];
    var contentBox = domGeom.getContentBox(myDivNode);
    alert(contentBox.w);

    // This is how to set width/height
    domGeom.setContentSize(myDivNode, {w: 100, h: 100});
});

Source: https://dojotoolkit.org/reference-guide/1.7/dojo/contentBox.html

Sign up to request clarification or add additional context in comments.

Comments

1

you can't get width value of element that wasn't appended to document.

so you should append it to page, than you can get width,

here is a working demo

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.