Home  >  Article  >  Web Front-end  >  How to remove element content with jquery

How to remove element content with jquery

WBOY
WBOYOriginal
2021-11-24 15:28:342469browse

Method: 1. Use the children() and remove() methods to delete the content of the specified element. The syntax is "$(element).children().remove();"; 2. Use the empty() method Delete the content of the specified element, the syntax is "$(element).empty();".

How to remove element content with jquery

The operating environment of this tutorial: windows7 system, jquery1.10.0 version, Dell G3 computer.

How to remove element content in jquery

In jquery, you can set the id attribute for part of the content tag within the tag, and obtain the part through the id Content object.

If you need to delete elements and content, you can generally use the following two jQuery methods:

  • remove() - delete the selected element (and its sub-elements)

  • empty() - Delete child elements from the selected elements

Let’s take a look at the use of these two methods through examples. The examples are as follows :

1. Use the children() method to return all direct child elements of the selected element, and then use the jQuery remove() method to delete the selected element and its child elements.

<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").children().remove();
  });
});
</script>
</head>

<body>

<div id="div1" style="height:120px;width:300px;border:1px solid black;background-color:yellow;">
<p>This is some text in the div.</p>
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
</div>

<br>
<button>删除 div 元素</button>

</body>
</html>

Output result:

How to remove element content with jquery

2. The jQuery empty() method deletes the child elements of the selected element.

<!DOCTYPE html>
<html>
<head>
<script src="/jquery/jquery-1.11.1.min.js"></script>
<script>
$(document).ready(function(){
  $("button").click(function(){
    $("#div1").empty();
  });
});
</script>
</head>
<body>
<div id="div1" style="height:100px;width:300px;border:1px solid black;background-color:yellow;">
This is some text in the div.
<p>This is a paragraph in the div.</p>
<p>This is another paragraph in the div.</p>
</div>
<br>
<button>清空 div 元素</button>
</body>
</html>

Output results:

How to remove element content with jquery

Recommended related video tutorials: jQuery video tutorial

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

Statement:
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