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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/652917/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:31:55  来源:igfitidea点击:

In jQuery I want to remove all HTML inside of a div

jquery

提问by mrblah

I have a div and I want to remove all the HTML inside of that div.

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

How can I do this?

我怎样才能做到这一点?

回答by Paolo Bergantino

You want to use the emptyfunction:

你想使用函数:

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

回答by bart

I don't think empty()or html()is what you are looking for. I guess you're looking for something like strip_tagsin PHP. If you want to do this, than you need to add this function:

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

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

Suppose this is your HTML:

假设这是您的 HTML:

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

And then you do:

然后你做:

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

Which will result in:

这将导致:

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

回答by karim79

Another way is just to set the html to the empty string:

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

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

回答by Chriz

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

回答by mynameistechno

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

回答by reza.cse08

suppose you have a html like this

假设你有一个这样的 html

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

if you want all html under "first" div to remove permanently. just use this

如果您希望永久删除“第一个”div 下的所有 html。就用这个

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

result will be like this

结果会是这样

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

  </div>
</div>

for temporary(if you want to add them again) we can try detach() like

对于临时(如果您想再次添加它们),我们可以尝试 detach() 之类的

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