Epik
Epik

Reputation: 3357

Using JavaScript to set the height and width of a div?

I am trying to set the height and width of a div through javascript and to no avail. I have tried numerous things and had no luck so far please advise me where i am going wrong? I thought this would just be straight forward...

I am not sure what the problem is here, I cannot use CSS in this case to set the variables i need to do it in JavaScript that is another topic all together though.

<div id="demo">Demo Div</div>

<script>
    var test = document.getElementById("demo");
    test.style.width = "100px";
    test.style.height = "100px";
    test.style.cssText = 'border:1px solid black;'
</script>

Thank you in advance.(I am open to a jQuery alternative as well)

-Epik-

Upvotes: 0

Views: 1722

Answers (2)

question
question

Reputation: 361

The cssText is overwriting the height and width you set, as well as any other styling you had.

JQuery, thanks to nnnnnn:

$("#demo").css({
    width : "100px",
    height : "100px",
    border : '1px solid black'
});

I would recommend trashing cssText for border like so:

var test = document.getElementById("demo");
test.style.border = '1px solid black';
test.style.width = "100px";
test.style.height = "100px";

But if you really need cssText, then use it first:

var test = document.getElementById("demo");
test.style.cssText = 'border:1px solid black;';
test.style.width = "100px";
test.style.height = "100px";

The last viable solution is to do it all using cssText:

var test = document.getElementById("demo");
test.style.cssText = 'border:1px solid black; width: 100px; height: 100px';

Upvotes: 0

nnnnnn
nnnnnn

Reputation: 150010

The problem is that your last line is setting cssText, which overwrites the styles set on the first two lines rather than adding to them. Try this instead:

var test = document.getElementById("demo");
test.style.width = "100px";
test.style.height = "100px";
test.style.border = '1px solid black'

Demo: http://jsfiddle.net/ZtyfB/

And since you mentioned jQuery, here's one way you could use it to do the same thing:

$("#demo").css({
    width : "100px",
    height : "100px",
    border : '1px solid black'
});

Upvotes: 6

Related Questions