.replaceAll()

jQuery

.replaceAll()


.replaceAll( target ) Returns: jQuery

Description: Replace each target element with the set of matched elements.

  • version added: 1.2.replaceAll( target )

    • target
      Type: Selector
      A selector expression indicating which element(s) to replace.

The .replaceAll() method is corollary to .replaceWith(), but with the source and target reversed. Consider this DOM structure:

1
2
3
4
5
                                
<div class="container">
<div class="inner first">Hello</div>
<div class="inner second">And</div>
<div class="inner third">Goodbye</div>
</div>

We can create an element, then replace other elements with it:

1
                                
$('<h2>New heading</h2>').replaceAll('.inner');

This causes all of them to be replaced:

1
2
3
4
5
                                
<div class="container">
<h2>New heading</h2>
<h2>New heading</h2>
<h2>New heading</h2>
</div>

Or, we could select an element to use as the replacement:

1
                                
$('.first').replaceAll('.third');

This results in the DOM structure:

1
2
3
4
                                
<div class="container">
<div class="inner second">And</div>
<div class="inner first">Hello</div>
</div>

From this example, we can see that the selected element replaces the target by being moved from its old location, not by being cloned.

Example:

Replace all the paragraphs with bold words.

1
2
3
4
5
6
7
8
9
10
11
12
13
                                  
<!DOCTYPE html>
<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<p>Hello</p>
<p>cruel</p>
<p>World</p>
<script> $("<b>Paragraph. </b>").replaceAll("p"); </script>
</body>
</html>