admin管理员组

文章数量:1278978

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.

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.

Share Improve this question asked Sep 11, 2012 at 21:05 DónalDónal 187k177 gold badges584 silver badges844 bronze badges 0
Add a ment  | 

5 Answers 5

Reset to default 5

Why all these needlessly plex 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.

Try:

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

html = $(html).html();

alert(html);

http://jsfiddle/TTEwm/

Try .unwrap() -

$("#inner").unwrap();

If html string always look like in your example you can use this simple code

var html = "<div class='outer'><div class='inner'>lots more html in here</div></div>";
html = html.slice(19,-6)

You can do something like this:

var html = "<div id='inner'>" + html.split("<div id='inner'>")[1].split("</div>")[0] + "</div>";

But you may want to add more protection for variations (in case you have the bad habit of not writing code using the same conventions), e.g "inner" or <DIV>

Demo

本文标签: javascriptremove outer divStack Overflow