使用jQuery如何删除一个div中所有的HTML内容?

75
我有一个 div,我想删除该 div 内部的所有 HTML。
我如何做到这一点?
6个回答

147
你想要使用 empty 函数:
$('#mydiv').empty();

74

我不认为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>

5
我认为他的意思是要清空所有内容。尽管如此,他的回答对于后代来说是一个好答案。 - Pekka
30
我个人会直接使用$("#foo").html($("#foo").text());。 - Killroy
他并没有说他是否想要纯文本结果,但是这个答案对我很有用 :) - detay
非常好,稍作修改后,它也可以很好地用于输入字段。非常感谢你。 - shadowhorst

12

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

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

0
  function stripsTags(text)
  {
    return $.trim($('<div>').html(text).text());
  }

如果文本是<script type="text/javascript">alert('sasa');</script>,它会弹出警报,因此不安全。 - umpirsky

0
假设你有一个像这样的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();

0
var htmlJ = $('<p><span>Test123</span><br /><a href="http://www.google.com">goto Google</a></p>');
console.log(htmlJ.text()); // "Test123goto Google"

如果文本是<script type="text/javascript">alert('sasa');</script>,它会弹出警报,因此不安全。 - umpirsky

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接