在 jQuery 中,我想删除 div 中的所有 HTML

我有一个 div,我想删除该 div 中的所有 HTML。

我怎么能这么做?

103140 次浏览

你想使用 空荡荡的函数:

$('#mydiv').empty();

另一种方法是将 html 设置为空字符串:

$('#mydiv').html('');

我不认为 empty()html()是你正在寻找的。我猜您正在寻找类似于 PHP 中的 strip_tags。如果你想这样做,那么你需要添加这个函数:

jQuery.fn.stripTags = function() {
return this.replaceWith( this.html().replace(/<\/?[^>]+>/gi, '') );
};

假设这是您的 HTML:

<div id='foo'>This is <b>bold</b> and this is <i>italic</i>.</div>

然后你做到了:

$("#foo").stripTags();

这将导致:

<div id='foo'>This is bold and this is italic.</div>
var htmlJ = $('<p><span>Test123</span><br /><a href="http://www.google.com">goto Google</a></p>');
console.log(htmlJ.text()); // "Test123goto Google"
  function stripsTags(text)
{
return $.trim($('<div>').html(text).text());
}

假设你有一个这样的 html

<div class="prtDiv">
<div class="first">
<div class="hello">Hello</div>
<div class="goodbye">Goodbye</div>
</div>
</div>

如果你想要“ first”div 下的所有 html 永久删除,只需要使用这个

$('.first').empty();

结果是这样的

<div class="prtDiv">
<div class="first">


</div>
</div>

为了临时(如果您想再次添加它们) ,我们可以尝试 detach () ,比如

$('.first').detach();