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


73

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

我怎样才能做到这一点?

Answers:



72

我不认为,empty()或者html()您正在寻找什么。我猜您正在寻找类似strip_tagsPHP的东西。如果要执行此操作,则需要添加以下功能:

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
我认为他的意思是删除所有内容。仍然+1为后代提供了很好的答案。
佩卡

29
我个人只是做$(“#foo”)。html($(“#foo”)。text());
Killroy 2010年

他的意思不是说他是否想要纯文本结果,但是这个答案对我仍然
有用

太好了,做了一些细微的更改,对于输入字段也很有效。非常感谢你。
shadowhorst 2012年

11

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

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

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

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();
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.