3

在我的 JavaScript 代码中,我有一个包含以下内容的字符串:

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

我需要将其转换为字符串

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

我已经在我的项目中使用了 jQuery,所以我可以在必要时使用它来完成它。

4

5 回答 5

5

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.

于 2012-09-11T21:15:13.663 回答
3

尝试:

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

html = $(html).html();

alert(html);

http://jsfiddle.net/TTEwm/

于 2012-09-11T21:07:19.830 回答
2

试试.unwrap()——

$("#inner").unwrap();
于 2012-09-11T21:07:18.233 回答
0

如果 html 字符串在您的示例中总是如此,您可以使用这个简单的代码

var html = "<div class='outer'><div class='inner'>lots more html in here</div></div>";
html = html.slice(19,-6)
于 2012-09-11T21:12:12.277 回答
0

你可以这样做:

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

但是您可能希望为变化添加更多保护(如果您有不使用相同约定编写代码的坏习惯),例如"inner"<DIV>

演示

于 2012-09-11T21:21:06.227 回答