146

I have a div with id="div_register". I want to set its width dynamically in JavaScript.

I am using this following code:

getElementById('div_register').style.width=500;

but this line of code isn't working.

I also tried using the units px like the following, still no luck:

getElementById('div_register').style.width='500px';

and

getElementById('div_register').style.width='500';

and

getElementById('div_register').style.width=500px;

but none of this code is working for me.

I don't know what's going wrong.

I am using Mozilla Firefox.

EDIT

<html>
    <head>
        <title>Untitled</title>
        <script>
            function show_update_profile() {
                document.getElementById('black_fade').style.display='block';
                //document.getElementById.('div_register').style.left=((window.innerWidth)-500)/20;
                document.getElementById('div_register').style.height= "500px";
                document.getElementById('div_register').style.width= '500px';
                //alert('kutta');
                  document.getElementById('div_register').style.display='block';
                document.getElementById('register_flag').value= 1;
                document.getElementById('physical_flag').value= 0;
                document.getElementById('cultural_flag').value= 0;
                document.getElementById('professional_flag').value= 0;
                document.getElementById('lifestyle_flag').value= 0;
                document.getElementById('hobby_flag').value= 0;
                //alert(window.innerWidth);
            }
        </script>
        <style>
            .white_content {
                display:none;
            }
        </style>
    </head>
    <body>
        <div id="main">
            <input type="button" onclick="javascript:show_update_profile();" id="show" name="show" value="show"/>
        </div>
        <div id="div_register">
            <table cellpadding="0" cellspacing="0" border="0">
                <tr>
                    <td>
                      welcome 
                    </td>
                </tr>
            </table>
        </div>
    </body>
</html>
Gerold Broser
  • 14,080
  • 5
  • 48
  • 107
Saswat
  • 12,320
  • 16
  • 77
  • 156
  • Have you tried to setting the width after the `onload` event has occured? – Cyclonecode Apr 12 '12 at 06:04
  • 2
    Did you check, that `div_register` is the right id of your element? Maybe give us some html, too... `style.width="500px";` should be right. – powerMicha Apr 12 '12 at 06:05
  • i have set document.getElementById('div_register').style.display='block', and then set document.getElementById('div_regsiter').style.width='500px'; – Saswat Apr 12 '12 at 06:05
  • 1
    For what its worth, you have typos in the word "document" in lines 3 & 4 of your function...which would most definitely keep it from working. – Daniel Szabo Apr 12 '12 at 06:42
  • 1
    use `onclick="show_update_profile()"` instead of `onclick="javascript:show_update_profile()"` – Tejasva Dhyani Apr 12 '12 at 06:43

7 Answers7

286

The properties you're using may not work in Firefox, Chrome, and other non-IE browsers. To make this work in all browsers, I also suggest adding the following:

document.getElementById('div_register').setAttribute("style","width:500px");

For cross-compatibility, you will still need to use the property. Order may also matter. For instance, in my code, when setting style properties with JavaScript, I set the style attribute first, then I set the properties:

document.getElementById("mydiv").setAttribute("style","display:block;cursor:pointer;cursor:hand;");
document.getElementById("mydiv").style.display = "block";
document.getElementById("mydiv").style.cursor = "hand";

Thus, the most cross-browser compatible example for you would be:

document.getElementById('div_register').setAttribute("style","display:block;width:500px");
document.getElementById('div_register').style.width='500px';

I also want to point out that a much easier method of managing styles is to use a CSS class selector and put your styles in external CSS files. Not only will your code be much more maintainable, but you'll actually make friends with your Web designers!

document.getElementById("div_register").setAttribute("class","wide");

.wide {
    display:block;
    width:500px;
}

.hide {
    display:none;
}

.narrow {
    display:block;
    width:100px;
}

Now, I can easily just add and remove a class attribute, one single property, instead of calling multiple properties. In addition, when your Web designer wants to change the definition of what it means to be wide, he or she does not need to go poking around in your beautifully maintained JavaScript code. Your JavaScript code remains untouched, yet the theme of your application can be easily customized.

This technique follows the rule of separating your content (HTML) from your behavior (JavaScript), and your presentation (CSS).

Vaibhav Jain
  • 1,939
  • 26
  • 36
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
  • 1
    Won't this override all other style attributes? As mentioned in a comment to the question, `display: block` was also set. – powerMicha Apr 12 '12 at 06:07
  • 2
    Set everything at once when using the style attribute. In my example from my own tested and working code, I put `display:block;cursor:pointer;cursor:hand` all in the same setAttribute call. If you want your life to be easier, use a progressive JavaScript library like jQuery. The only reason I used raw JavaScript in my code is because it was for embed code on client websites, so the actual environments would differ from site to site, and the easiest way to avoid library conflicts in the wild is to just not use them. – jamesmortensen Apr 12 '12 at 06:10
  • 1
    I added another example that uses class attributes. This technique follows the rule of separating your content (HTML) from your behavior (JavaScript), and your presentation (CSS). It also abstracts away the actual details of the styling by giving it an easy-to-work-with className. – jamesmortensen Apr 12 '12 at 06:18
  • @jmort: +1. But just in the name of accuracy, Chrome/FireFox/Safari all support the manipulation of the attributes in question (ex: element.style.height, element.style.width, etc.) – Daniel Szabo Apr 12 '12 at 06:51
  • Hmmm, I know that in my own code, to get it to play nice with IE7, I had to follow some very specific steps that were discovered through very painful trial and error. It might be that IE7 wouldn't work properly with setAttribute... I don't remember exactly, so I'll leave this as an exercise for the reader and will remove the part about chrome/FF, etc. I know the code works, even if I might not be explaining it correctly. :) – jamesmortensen Apr 12 '12 at 06:56
  • @ajax81 - I edited out the browser-specific parts and just used the words "browser cross-compatibility". Thanks for helping to clean this up. – jamesmortensen Apr 12 '12 at 06:58
  • To add a style instead of overwriting, you could also use the low level `style.cssText += " width:500px;"`, not pretty but works. You could even use replace on it. https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration/cssText – RiZKiT Feb 07 '20 at 15:31
21

These are several ways to apply style to an element. Try any one of the examples below:

1. document.getElementById('div_register').className = 'wide';
  /* CSS */ .wide{width:500px;}
2. document.getElementById('div_register').setAttribute('class','wide');
3. document.getElementById('div_register').style.width = '500px';
jamesmortensen
  • 33,636
  • 11
  • 99
  • 120
Valli69
  • 8,856
  • 4
  • 23
  • 29
2

Fix the typos in your code (document is spelled wrong on lines 3 & 4 of your function, and change the onclick event handler to read: onclick="show_update_profile()" and you'll be fine. @jmort's advice is good - simply set up 2 css classes that you switch between in javascript - it'll make things easier.

You might also check out element.addEventListener for assigning event handlers to your elements.

Daniel Szabo
  • 7,181
  • 6
  • 48
  • 65
0

The onclick attribute of a button takes a string of JavaScript, not an href like you provided. Just remove the "javascript:" part.

jpsimons
  • 27,382
  • 3
  • 35
  • 45
0

If you remove the javascript: prefix and remove the parts for the unknown ids like 'black_fade' from your javascript code, this should work in firefox

Condensed example:

<html>
    <head>
        <script type="text/javascript">
            function show_update_profile() {
               document.getElementById('div_register').style.height= "500px";
               document.getElementById('div_register').style.width= "500px";
               document.getElementById('div_register').style.display='block';
               return true;
           }
        </script>
        <style>
           /* just to show dimensions of div */
           #div_register
           {
                background-color: #cfc;
           }
        </style>
    </head>
    <body>
        <div id="main">
            <input type="button" onclick="show_update_profile();" value="show"/>
        </div>
        <div id="div_register">
            <table>
                <tr>
                   <td>
                     welcome 
                   </td>
                </tr>
            </table>
        </div>
    </body>
</html>
powerMicha
  • 2,753
  • 1
  • 24
  • 31
  • +1 on removing the "javascript:". That is an outdated construct from the long-gone days of Web 1.0. – jamesmortensen Apr 12 '12 at 07:02
  • Then please add it to your example, otherwise the script will fail - btw: Do you know the `Firebug` plugin for Firefox? This will help you a lot – powerMicha Apr 12 '12 at 09:23
  • actualy there was nothing wrong in my script.........becaquse i was using a pop up box....that was offtopic, because my script worked well all along, using javascript: it worked all good, may be its outdated bt this wasnt an error...the problem was with updating the width dynamicaly...and jmort's solution helped me outcome the solution – Saswat Apr 12 '12 at 09:27
  • Sure. I just wanted to point out, that these parts were missing in the example, which leads to other problems. So everthing is fine now – powerMicha Apr 12 '12 at 10:02
0

Be careful of span!

myspan.styles.width='100px' doesn't want to work.

Change the span to a div.

Andy B
  • 629
  • 8
  • 15
  • 2
    This is because `span` is an inline element by default, and therefore won't obey any sizing set on it. Changing its CSS to `display: block`, `display: flex`, or `display: inline-block` will cause it to work properly just like a `div` (a block element by default). – Daniel T. Sep 08 '16 at 03:38
  • 2
    The question never mentioned a *span*, and no answer suggested using one either. I don't see how this answer helps at all. – Vince Bowdren Nov 30 '16 at 13:38
  • 1
    Weird, this was a year ago so not sure why either!! ^_^ – Andy B Dec 02 '16 at 14:05
  • 1
    And change `styles.width` to `style.width`. :) – RiZKiT Feb 07 '20 at 15:22
-3

You have to use document. The Document interface represents any web page loaded in the browser and serves as an entry point into the web page's content,

know more

document.getElementById('div_register').style.width='500px';
MD SHAYON
  • 7,001
  • 45
  • 38