155

Is it possible to set width or height of HTML element (ex. <div>) in JavaScript in Standards Mode?

Note the following code:

<html>
<script language="javascript" type="text/javascript">
    function changeWidth(){
        var e1 = document.getElementById("e1");
        e1.style.width = 400;
    } 
</script>
<body>
    <input type="button" value="change width" onclick="changeWidth()"/>
    <div id="e1" style="width:20px;height:20px; background-color:#096"></div>
</body>
</html>

When user presses the change width button, the <div>'s width should change.

It works fine when doctype declaration determines Quirks Mode. In Standards Mode I'm unable to change the element's size this way

Is it possible to manipulate the size of an element in Standards Mode? How to bypass this disfunctionality?

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
rafalry
  • 2,620
  • 6
  • 24
  • 39

2 Answers2

234

Try declaring the unit of width:

e1.style.width = "400px"; // width in PIXELS
Community
  • 1
  • 1
Alexandre Perez
  • 3,355
  • 3
  • 21
  • 21
  • 1
    Ahaha.. i mean "meow" (c). I've spend about an hour, trying to figure out why style is not applied. Thanks! – Vitalii Vasylenko Nov 29 '17 at 17:28
  • 2
    It's worth mentioning the width does not including margins, and when `box-sizing: border-box;`, the width will include borders, elsewise the width doesn't include borders. –  Apr 06 '18 at 06:33
  • 1
    Fairly obnoxious that `window.innerWidth` returns just an integer without any units attached... – ArtOfWarfare Jun 26 '21 at 04:23
46

The style property lets you specify values for CSS properties.

The CSS width property takes a length as its value.

Lengths require units. In quirks mode, browsers tend to assume pixels if provided with an integer instead of a length. Specify units.

e1.style.width = "400px";
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335