1

I'm trying to remove a surrounding div section from the DOM by using the following simple code:

document.getElementById("1").outerHTML = document.getElementById("1").innerHTML;
<p>
    Part 1
    <div id="1">
        <span id ="2">
            Part 2
        </span>
        Part 3
    </div>
    Part 4
</p>

The expected output applying the script is that all parts are within one single line. However they are not. When I manually remove the div section from the HTML code they are in one line. Any ideas what I'm doing wrong?

Thank you,

Andreas

  • Try setting the innerHTML of the `

    ` tag. You may have to nest `

    ` inside another tag for this, or keep a track of the text in the `

    ` tag.

    – Vivek Jain Nov 30 '15 at 09:39

3 Answers3

1

You cannot nest a block level element inside inline elements in HTML. In other words, a div inside a p is invalid in all standards of HTML. Moreover, when using a conforming HTML parser, it is impossible to place a <div> element inside a <p> in the DOM because the opening <div> tag will automatically close the <p> element.

Your code is correct if the surrounding element was a div.

<div>
    Part 1
    <div id="1">
        <span id ="2">
            Part 2
        </span>
        Part 3
    </div>
    Part 4
</div>
Mr Lister
  • 45,515
  • 15
  • 108
  • 150
Prashant Ghimire
  • 4,890
  • 3
  • 35
  • 46
  • Dear Prashant, thank you for the hint. Unfortunately I don't have control over the HTML part. However it is good to know that the HTML is invalid. – Andreas Purde Dec 01 '15 at 17:54
0

document.getElementById("1").outerHTML will return (1):

<div id="1">
   <span id ="2">
      Part 2
   </span>
   Part 3
</div>

document.getElementById("1").innerHTML; will return (2):

<span id ="2">
   Part 2
</span>
Part 3

Your code means: Replace (1) with (2)

Tân
  • 1
  • 15
  • 56
  • 102
0

The problem is due to the wrong HTML structure. Because, P element "cannot contain block-level elements (including P itself)".

Check this link for more info

Solution: Replace the extreme P element with div. Check the link(Working Code) below.

<div id="3">
    Part 1
    <div id="1">
        <span id ="2">
            Part 2
        </span>
        Part 3
    </div>
    Part 4
</div>

var newHtml = document.getElementById('1').innerHTML;
document.getElementById("1").outerHTML=newHtml;

Working Code

Community
  • 1
  • 1
SSS
  • 92
  • 4
  • Dear Santhosh, thank you for the hint. Unfortunately I don't have control over the HTML part. However it is good to know that the HTML is invalid. – Andreas Purde Dec 01 '15 at 17:55