Derek
Derek

Reputation: 12378

Calculating html element (div) width with javascript/dojo?

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?

Upvotes: 0

Views: 2520

Answers (2)

user24950814234
user24950814234

Reputation: 2037

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

Upvotes: 3

Okan Kocyigit
Okan Kocyigit

Reputation: 13421

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

Upvotes: 1

Related Questions