Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove outer div

In my JavaScript code I have a string that contains something like:

var html = "<div class='outer'><div id='inner'>lots more html in here</div></div>";

I need to convert this to the string

var html = "<div id='inner'>lots more html in here</div>";

I'm already using using jQuery in my project, so I can use this to do it if necessary.

like image 294
Dónal Avatar asked Oct 17 '25 10:10

Dónal


1 Answers

Why all these needlessly complex answers?

//get a reference to the outer div
var outerDiv = document.getElementById('outerDivId');//or $('#outerDivId')[0];
outerDiv.outerHTML = outerDiv.innerHTML;

And that's it. Just set the outerHTML to the inner, and the element is no more.


Since I had overlooked that you're dealing with an HTML string, it needs to be parsed, first:

var tempDiv = document.createElement('div');
tempDiv.innerHTML = htmlString;
var outerDiv = tempDiv.getElementsByTagName('div')[0];//will be the outer div
outerDiv.outerHTML = outerDiv.innerHTML;

And you're done.

like image 54
Elias Van Ootegem Avatar answered Oct 19 '25 23:10

Elias Van Ootegem



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!