Methods used to remove text for the selected element.
We can remove the text in these different ways.
Removes the selected element from the DOM
We have different types in remove() method
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery Remove Methods Example</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
<style>
.highlight {
background-color: yellow;
}
</style>
</head>
<body>
<div id="exampleElement" class="highlight" title="Example Title">
<p>This element has some attributes and a class.</p>
</div>
<script>
// Using remove() to remove the entire element
$("#exampleElement").remove();
// Creating a new element with the same attributes and class
var newElement = $("<div id='newElement' class='highlight' title='New Title'><p>New Element</p></div>");
// Appending the new element to the body
$("body").append(newElement);
// Using removeAttr() to remove the 'title' attribute
newElement.removeAttr('title');
// Using removeClass() to remove the 'highlight' class
newElement.removeClass('highlight');
// Using removeProp() to remove the 'id' property
newElement.removeProp('id');
</script>
</body>
</html>
empty() Method Removes all child elements of the selected element detach() Method Removes the selected element from the DOM, but keeps a copy
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>jQuery empty() and detach() Example</title>
<script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
</head>
<body>
<div id="exampleContainer">
<p>Existing content.</p>
<span>Another element.</span>
</div>
<script>
// Using empty() to remove all child elements and content
$("#exampleContainer").empty();
// Creating a new element
var newDiv = $("<div>New content added</div>");
// Appending the new element to the container
$("#exampleContainer").append(newDiv);
// Using detach() to remove the new element from the DOM but keep a copy
var detachedElement = newDiv.detach();
// Appending the detached element back to the container
$("#exampleContainer").append(detachedElement);
</script>
</body>
</html>
The Concepts and codes you leart practice in Compilers till you are confident of doing on your own. A Various methods of examples, concepts, codes availble in our websites. Don't know where to start Down some code examples are given for this page topic use the code and compiler.