SKing7
SKing7

Reputation: 2356

blank div on ie but not blank

for example have a div,html code below

<div id="testDiv"></div>

but when i set the innerHTML property of the div(id=testDiv) on ie ,see the code below:

document.getElementById('testDiv').innerHTML= '';

and the div will have a height and width,not a blank div any more
so that is why??
if i want the div is a blank div when set the innerHTML=''(if do not set the display:none),how should i do?
now show the test code(different results runing on ie7 and chrome)

<!DOCTYPE>
<html>
<head>
<style>
        #bl{background:red;}
</style>
<script type="text/javascript">
function f(a){
    var t=document.getElementById("bl");
    t.innerHTML=a;
}
</script>
</head>
<body>
    <button type="button"  onclick="f('')">test</button>
    <div id="bl"></div>
</body>
</html>

Upvotes: 2

Views: 214

Answers (2)

Mr Lister
Mr Lister

Reputation: 46579

In your function, check if the text is '', and if so, remove the child node from the div. instead of setting its value.

if (a=='') t.removeChild(t.childNodes[0]);
else t.innerHTML=a;

Checked in IE8 and in IE8's compatibility mode (so it should work in IE7 too).

For more stability, you can remove all child nodes from t, like so...

if (a=='') {while (t.hasChildNodes() t.removeChild(t.childNodes[0]);}
else t.innerHTML=a;

Upvotes: 2

Ilia Frenkel
Ilia Frenkel

Reputation: 1977

I think this is a known IE behaviour. In addition to setting innerHTML to empty string you can also set font-size to 0.

Upvotes: 1

Related Questions