Home > Web Front-end > Front-end Q&A > How to remove elements in jquery

How to remove elements in jquery

WBOY
Release: 2022-04-08 12:03:30
Original
2452 people have browsed it

Method: 1. Use the remove() method to remove elements. This method is used to delete specified elements. The syntax is "element object.remove();"; 2. Use the empty() method to remove elements. The method is used to delete all child elements of the specified element. The syntax is "element object.empty();".

How to remove elements in jquery

The operating environment of this tutorial: windows10 system, jquery3.2.1 version, Dell G3 computer.

How to remove elements with jquery

You can delete selected elements and sub-elements through jquery's remove() and empty() methods,

  • remove() ,

  • empty() only deletes the child elements of the selected element,

Let’s take a look at them separately:

1. Use the remove method

remove() method to remove the selected element, including all text and child nodes.

This method will also remove the data and events of the selected element.

The syntax is:

$(selector).remove()
Copy after login

The example is as follows:

<html>
<head>
<meta charset="utf-8">
<title>123</title>
<script src="js/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("p").remove();
});
});
</script>
</head>
<body>
<p>这是一个段落。</p>
<p>这是另一个段落。</p>
<button>移除所有P元素</button>
</body>
</html>
Copy after login

Output result:

How to remove elements in jquery

2. Use the empty method

empty() method to remove all child nodes and content of the selected element.

Note: This method does not remove the element itself, or its attributes.

The syntax is:

$(selector).empty()
Copy after login

The example is as follows:

<html>
<head>
<meta charset="utf-8">
<title>123</title>
<script src="js/jquery.min.js">
</script>
<script>
$(document).ready(function(){
$("button").click(function(){
$("div").empty();
});
});
</script>
</head>
<body>
<div style="height:100px;background-color:yellow">
这是一些文本。
<p>这是div块中的一个段落。</p>
</div>
<p>这是div块外部的一个段落。</p>
<button>移除div块中的内容</button>
</body>
</html>
Copy after login

Output result:

How to remove elements in jquery

Related video tutorials Recommended: jQuery video tutorial

The above is the detailed content of How to remove elements in jquery. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template