I've noticed very strange behavior using innerHTML
:
var elem = document.body;
elem.innerHTML = '<p> <div> Inner div </div> </p>';
What DOM you expect to see after running this code?
Like this?
<body>
<p>
<div> Inner div </div>
</p>
</body>
Incorrect answer! Because you will see the following DOM instead:
<body>
<p></p>
<div> Inner div </div>
<p></p>
</body>
It works like that on Chrome, Safari, MS Edge, IE11 (works like expected only on Firefox).
Does anyone know why the heck it works like this on most browsers?
I know it's semantically wrong to add div
s inside p
but I can add them by appendChild
or even by innerHTML
on p
element itself!
P.S. It pops out divs from any level:
elem.innerHTML = '<p><span> It breaks divs <div> at any </div> level </span></p>'
results in an absolute mess:
<body>
<p>
<span> It breaks divs </span>
</p>
<div> at any </div>
level
<p></p>
</body>