Removing wrapper div without Jquery (raw javascript)
Asked Answered
S

3

5

I know there is a solution with Jquery called unwrap, but I am writing "raw" JavaScript. I didn't find any solution without jQuery.

I'd like to remove a div like so:

<div><div id="mydiv">Important text here</div></div>

After removal of "mydiv":

<div>Important text here</div>

What should I do, I'd like to know the theory.

Thanks in advance.

Synoptic answered 20/7, 2012 at 13:24 Comment(2)
did you try browsing jQuery's source?Kovacev
@JosephtheDreamer, yes, but I couldn't really figure it out, I am not a really jQuery junkie.Synoptic
E
13

shouldn't this line work

 document.getElementById("mydiv").outerHTML = document.getElementById("mydiv").innerHTML

See this JSBin Example (inspect the element)

Exorbitant answered 20/7, 2012 at 13:31 Comment(4)
Thanks it worked! Now i'll read more about this mysterious "outerHTML" property.Synoptic
Best solution, because it keeps the position in DOM tree!Announcer
I'm finding the events attached to elements in the innerHtml get lost. Is there a trick to keep those?Yearbook
This worked for me for my custom web-component. It allowed me to remove <my-custom-tag></ my-custom-tag> around the elements I want to keep.Strangulate
I
0

You need to use removeChild method for that:

var divToRemove = document.getElementById('mydiv').;
var tmpStr = divToRemove.innerHTML;
var parent = divToRemove.parentNode;
parent.removeChild(divToRemove);
parent.inerHTML(tmpStr);
Institutionalism answered 20/7, 2012 at 13:28 Comment(1)
This will completely rewrite the parent innerHTML which isn't good. (I may have more text in-between)Synoptic
C
0

Try

​var el = document.getElementById('mydiv');
var text = el.innerText; //or el.innerHTML
    el.parentNode.innerHTML = text;
​

This would replace the html of mydiv's parent with the content of mydiv.

Clop answered 20/7, 2012 at 13:28 Comment(3)
Same problem like @antyrat's answer.Synoptic
So will using outerHTML, but this isn't cross browser compatible. jsfiddle.net/gRoberts/ksCbT shows it working.Clop
I tested my code and it worked in: firefox chrome safari opera and internet explorer.Synoptic

© 2022 - 2024 — McMap. All rights reserved.