admin管理员组

文章数量:1304545

I'm trying to get div's width with javascript. Initially div's width is undefined, ie width depends on amount of text on it. Is it possible to get width of this kind of div? I'm trying to do it with following javascript code, but i'm getting width differerent from Chrome console when i'm inspecting div

var mydiv = document.getElementById("error_message");
var curr_width = mydiv.clientWidth;
alert(curr_width);

Thank you for your attention

I'm trying to get div's width with javascript. Initially div's width is undefined, ie width depends on amount of text on it. Is it possible to get width of this kind of div? I'm trying to do it with following javascript code, but i'm getting width differerent from Chrome console when i'm inspecting div

var mydiv = document.getElementById("error_message");
var curr_width = mydiv.clientWidth;
alert(curr_width);

Thank you for your attention

Share Improve this question asked Mar 9, 2011 at 17:29 andriyandriy 4,1649 gold badges50 silver badges72 bronze badges 5
  • Initially an unstyled div will have a width equal to its container's width. That's due to the default display:block styling. – zzzzBov Commented Mar 9, 2011 at 17:31
  • Can you add the HTML too ... im not sure your DIV will be the width of a the text within it ... its a BLOCK element – Manse Commented Mar 9, 2011 at 17:32
  • it's generated with document.write("<div id=\"error_message\">Wrong username or password!</div>"); and css is div#error_message{ display:block; position: absolute; padding: 2px; top: 0px; border: 1px solid #FF0000; background: #FFCCFF; font-family: Arial; font-size: 13px; color: #FF0000; } – andriy Commented Mar 9, 2011 at 17:34
  • And what is the width thats being shown in the alert ? what did you expect is to be ? – Manse Commented Mar 9, 2011 at 17:49
  • in alert it is 1008 and in console it is 183, so i'm expecting 183 – andriy Commented Mar 9, 2011 at 17:59
Add a ment  | 

3 Answers 3

Reset to default 6

use offsetWidth

clientWidth is calculated width, offsetWidth is the one in "Chrome inspect element" (i think)

also read the ments :P

While the OP doesn't specify one way or the other, if you happen to have jQuery available, you can always use this:

var curr_width = $('#error_message').width();

I managed to solve the problem! I was trying to create div directly in javascript, without defining div on html body. So inside of tag i've created

<div id="error_message" style="visibility:hidden;"></div>

and it's worked! Final javascript code is:

document.write("<div id=\"error_message\">Wrong username or password!</div>");
var mydiv = document.getElementById("error_message");
var curr_width = mydiv.offsetWidth;
alert(curr_width);

本文标签: htmlWrong div width when getting it with javascriptStack Overflow