I tried assigning <p><div></div>Hello</p>
to innerHTML, but it resulted in a different structure: <p></p><div></div>Hello<p></p>
. Is this a bug or expected behavior? Can't a <div>
element be placed inside <p>
element?
Code:
const div = document.createElement("div")
div.innerHTML = "<p><div></div>Hello</p>";
console.log(div.innerHTML);
Expected Output:
<p><div></div>Hello</p>
Result I get:
<p></p><div></div>Hello<p></p>
It is invalid HTML to put a <div>
inside of a <p>
. Because of this, many browsers will automatically close an open <p>
tag when they encounter a starting <div>
tag.
To know what content a specific type of element can validly contain, you can consult the "Technical summary" section of the element's documentation page on the MDN Web Docs or consult the HTML spec.
For paragraph elements, that documentation states their permitted content is "phrasing content".
Phrasing content is a specific content category that only a subset of elements belong to. A <div>
element is not phrasing content, so it can't go in a paragraph.