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>
3
Answers
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.By changing the sequence of tags you can get the desired result. As it is invalid html to have div tag as child of p tag.
Although most browsers will parse/validate the content provided through
innerHTML
, you can still achieve the desired output by creating the structure through JavaScript.See this example:
PS.: It is still invalid HTML though and not recommended. Most browsers will render the page in Quirks Mode then.