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?
This (was) by design.
An element
<p>should contain only inline elements, from HTML specs: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
<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
innerHTMLproperty 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>