如何使用 JQuery 删除元素的内容?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1474607/
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 11:33:07  来源:igfitidea点击:

How to remove an element's content with JQuery?

jquery

提问by Keith Donegan

Say I have a div and some content inside it.

假设我有一个 div 和其中的一些内容。

<div>
      Content
</div>

With JQuery, how do I empty the div without removing the div, only the content inside?

使用JQuery,如何清空div而不删除div,只删除里面的内容?

回答by CMS

You can use the emptyfunction to remove all the child nodes (all its content) of an element:

您可以使用empty函数删除元素的所有子节点(其所有内容):

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

The empty function will also remove all the event handlers and the jQuery internally cached data.

空函数还将删除所有事件处理程序和 jQuery 内部缓存数据。

回答by davethegr8

If the div has an id, you can do it like this:

如果 div 有一个 id,你可以这样做:

$('#id-of-div').html('');

Or you can do all classes of .class-of-div

或者你可以做 .class-of-div 的所有类

$('.class-of-div').html('');

Or just all divs

或者只是所有的div

$('div').html('');

EDIT: But empty()(above) would work better.

编辑:但是empty()(以上)效果会更好。

回答by halocursed

Html

html

<div id='emptythis'>
   Content
</div>

Jquery

查询

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

回答by Elyor

$( "div" ).remove( ".hello" );

Similar to .empty(), the .remove()method takes elements out of the DOM. Use .remove()when you want to remove the element itself, as well as everything inside it. In addition to the elements themselves, all bound events and jQuery data associated with the elements are removed. To remove the elements without removing data and events, use .detach()instead.

与 类似.empty(),该.remove()方法从 DOM 中取出元素。使用.remove()时要删除它里面的元素本身,以及一切。除了元素本身之外,所有与元素关联的绑定事件和 jQuery 数据都将被删除。要在不删除数据和事件的情况下删除元素,请.detach()改用。

reference

参考