jQuery replaceAll() Method
The replaceAll() method in jQuery is used to replace all selected elements with the new HTML elements.
This method accepts a parameter named âselectorâ which specifies the elements to be replaced.
Syntax
Following is the syntax of the replaceAll() method in jQuery −
$(content).replaceAll(selector)
Parameters
This method accepts the following parameters −
- content: The content to insert. It can be HTML, a jQuery object, or DOM elements.
- selector: A selector string or a jQuery object identifying the elements to be replaced.
Example 1
In the following example, we are using the replaceAll() method to replace all <div> elements with new <p> element −
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('<p>New Paragraph</p>').replaceAll('.old-paragraph');
})
});
</script>
</head>
<body>
<div class="old-paragraph">Old Paragraph 1</div>
<div class="old-paragraph">Old Paragraph 2</div>
<div class="old-paragraph">Old Paragraph 3</div>
<button>Click to replace</button>
</body>
</html>
When we click the button, all the <div> elements will be replaced by the new <p> element.
Example 2
In this example, we are replacing all the âlistâ elements with class âold-itemâ with a new list item −
<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$('<li>New Item</li>').replaceAll('.old-item');
})
});
</script>
</head>
<body>
<ul>
<li class="old-item">Old Item 1</li>
<li class="old-item">Old Item 2</li>
<li class="old-item">Old Item 3</li>
</ul>
<button>Click to replace</button>
</body>
</html>
After executing the above program, selected elements are replaced with the new list item.
jquery_ref_html.htm
Advertisements