Reputation: 1786
I am trying to set the width and height of a div in javascript but it is not being set. I have tried a lot but nothing is working. Here is what i have tried,
<div id="d1">asdasd</div>
<script>
var d = document.getElementById("d1");
d.style.width = "100px";
d.style.height = "100px";
d.style.cssText = 'border:1px solid black;'
</script>
Please check what is the problem!
Upvotes: 1
Views: 3313
Reputation: 26930
I think d.style.cssText
overwrites width
and height
properties
Try this:
var d = document.getElementById("d1");
d.style.width = "100px";
d.style.height = "100px";
d.style.cssText += 'border:1px solid black;'
Upvotes: 6
Reputation: 641
An alternate would be to define a new style element in CSS and simply set d.className
to that CSS element.
I guess
d.style.cssText
is problem
Upvotes: 1
Reputation: 8871
Your problem is with d.style.cssText = 'border:1px solid black;'
. it is overriding the width and height set by JS .
Check this fiddle:-
Upvotes: 2
Reputation: 701
HTML:
<div id="d1">asdasd</div>
Javascript
document.getElementById('d1').style.height = 90+'px';
working demo here ( works fine with chrome, din't check with other browsers )
Upvotes: 0
Reputation: 2835
I don't know what your problem is but I've used this and this worked
function fnc1()
{
document.getElementById("d1").style.width="100px";
document.getElementById("d1").style.height="100px";
document.getElementById("d1").style.backgroundColor="red";
}
Upvotes: 0
Reputation: 113866
As karaxuna mentioned, your d.style.cssText
is overwriting the width and height settings. Simply changing your code to either this:
var d = document.getElementById("d1");
d.style.width = "100px";
d.style.height = "100px";
d.style.border = '1px solid black';
or this:
var d = document.getElementById("d1");
d.style.cssText = 'border:1px solid black;'
d.style.width = "100px";
d.style.height = "100px";
works perfectly.
Upvotes: 3
Reputation: 4218
d.style.cssText = 'border:1px solid black;'
d.style.float="left";
d.style.width = "100px";
d.style.height = "100px";
You neeed to use float:left attribute.
Upvotes: 0
Reputation: 8117
Change sequence of your JS statements it will work i.e.
<script>
var d = document.getElementById("d1");
d.style.cssText = 'border:1px solid black;'
d.style.width = "100px";
d.style.height = "100px";
</script>
Better put width, height properties in style attribute only. i.e.
d.style.cssText = 'border:1px solid black; width:100px; height:100px'
or in CSS class
Upvotes: 0
Reputation: 151926
This works:
<div id="d1" style="border:1px solid black;">asdasd</div>
<script>
var d = document.getElementById("d1");
d.style.height = "200px";
</script>
http://jsfiddle.net/dandv/emnMb/4/
Upvotes: 1