Removing a <div> section with JS does not work as expected

Andreas Purde

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

Prashant Ghimire

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>

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Java

ConcurrentHashMap does not work as expected

From Dev

Method gsub does not work as expected

From Dev

printf specifier does not work as expected

From Dev

Loop in function does not work as expected

From Dev

Why does the regex work not as expected?

From Dev

Regex does not work as expected in interpreter

From Dev

PHP code does not work as expected

From Dev

MongoDB elemMatch does not work expected

From Dev

Synchronized method does not work as expected

From Dev

JQuery slideDown does not work as expected

From Dev

SQL Rank does not work as expected

From Dev

@VisibleForTesting does not work as expected

From Dev

Output for removing zeros in array does not come as expected?

From Dev

Update div when writing text does not work as expected

From Dev

Python: Boolean does not work as expected

From Dev

array filtering does not work as expected

From Dev

Scanf does not work as expected

From Dev

glBindAttribLocation does not work like expected

From Dev

.js ScrollTop to div or section tag

From Dev

Removing array element does not work

From Dev

Removing UIGestureRecognizer does not work

From Dev

Meteor JS Jade template does not work as expected

From Dev

MVVM binding with Vue.js does not work as expected

From Dev

memset() does not work as expected

From Dev

Scanf does not work as expected

From Dev

removeDuplicates does not work as expected

From Dev

Mutex does not work as expected

From Dev

substitute does not work as expected

From Dev

Js does not work as expected on my website even it works on codepen