How to change height and width of an element with Javascript


I’m currently trying to learn Javascript and I already have my first question.

How can I change the height and width of an element with Javascript?

I have tried and so far I can only change either the width or height but not both, doing something like this…


<script type = "text/javascript">
function changeSize(){document.getElementById('test').style.height = '200'}

<div id="test" onClick="changeSize()">Click Me</div>


And this works fine but if I try to change both height and width it doesn’t work. Doing something like this doesn’t work

function changeSize(){document.getElementById('test').style.height = '200' width=&#8217;200&#8217;}

Can some be so kind and help me with this?

200 what? Millimetres? Lightyears? Average elephant trunk lengths?
And you can’t set two properties at once like that.
And you can’t use curly apostrophes around string literals.

function changeSize() {
    var el = document.getElementById("test"); = "200px"; = "200px";

First of all thank you for your reply!

So, it is always better to create a variable and then change attributes through this variable, correct?

And you can’t use curly apostrophes around string literals.

I don’t know how this happened.


Not always. But in this case you need to refer to the same element in two places, so it’s better to call getElementById() once and assign the result to a variable than to call the same function twice.

Normally, you’d also like to do some error checking to prevent errors in case the specified element doesn’t exist. In that case using a variable would also make things much easier:

function changeSize(id) {
    var el = document.getElementById(id);
    if (el) { = "200px"; = "200px";

Hmm, very nice, thanks a lot for the extra advice.