Reputation: 3582
My code is:
<body>
<p id="tit"></p>
<script type="text/javascript">
try {
document.getElementById('tit').innerHTML = "<div>test</div>";
}
catch(e) {
alert(e)
}
</script>
</body>
alert [object Error]
in IE6/7/8, why?
Upvotes: 2
Views: 170
Reputation: 67080
This (was) by design.
An element <p>
should contain only inline elements, from HTML specs:
<!ELEMENT P - O (%inline;)* -- paragraph -->
It may be not so clear but it means that <p>
cannot contain a grouping element. Now in the <div>
specification we can read:
The DIV and SPAN elements, in conjunction with the id and class attributes, offer a generic mechanism for adding structure to documents. These elements define content to be inline (SPAN) or block-level (DIV) but impose no other presentational idioms on the content.
The <p>
element is not the only one that can contain only inline elements, headers (<h1>
, <h2>
,...) for example share the same behavior.
Many browsers allowed malformed HTML to be inserted via innerHTML
property so this strange behavior seemed to affect IE only. Newer version (IE 9 at this time) supports insertion of wrong HTML code via script so your HTML fragment won't cause an error (even if it's still not valid HTML).
My suggestion is to insert only valid HTML:
You may change the container element from <p>
to <div>
-or-
You may change the inserted element from <div>
to <span>
Upvotes: 1
Reputation: 1303
It seems to be the p element, if I use a div it works for me:
<div id="tit"></div>
<script type="text/javascript">
try {
document.getElementById('tit').innerHTML = "<div>test</div>";
}
catch (e) {
alert(e.message);
}
</script>
Instead, it doesn't with the p tag. You could also use jQuery and its .append() since it works very well.
Upvotes: 0