skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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.

    <div id='output'></div>
    
    const div = document.createElement("div")
    div.innerHTML += "<div><p></p>Hello</div>";
    console.log(div.innerHTML);
    document.getElementById('output').appendChild(div);
    
    Login or Signup to reply.
  3. 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:

    const pElement = document.createElement('p');
    const divElement = document.createElement('div');
    const textNode = document.createTextNode('Hello');
    
    pElement.appendChild(divElement);
    pElement.appendChild(textNode);
    
    // Not parsed as HTML.
    document.getElementById('outputCode').textContent = pElement.outerHTML;
    
    // Not parsed like through innerHTML.
    document.getElementById('outputElement').replaceChildren(pElement);
    
    // Parsed through innerHTML.
    document.getElementById('outputInner').innerHTML = pElement.outerHTML;
    div
    {
      outline: 1px solid blue;
      padding: 3px;
    }
    
    p
    {
      outline: 1px solid red;
      padding: 3px;
    }
    Text Output: <br />
    <code id="outputCode"></code>
    <hr />
    
    Quirks Output: <br />
    <section id="outputElement"></section>
    <hr />
    
    Standard Output: <br />
    <section id="outputInner"></section>
    <hr />

    PS.: It is still invalid HTML though and not recommended. Most browsers will render the page in Quirks Mode then.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search