jQuery replaceAll() example

The replaceAll() method replaces selected elements with new HTML elements.

Description

Replace each target element with the set of matched elements.

Syntax

$(selector).replaceAll( target ) 

Examples

Example 1

Replace all the paragraphs with bold words.
<!doctype html>
<html lang="en">

<head>
    <meta charset="utf-8">
    <title>replaceAll demo</title>
    <script src="https://code.jquery.com/jquery-3.4.1.js"></script>
</head>

<body>

    <p>Hello</p>
    <p>cruel</p>
    <p>World</p>

    <script>
        $("<b>Paragraph. </b>").replaceAll("p");
    </script>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

Example 2

<!DOCTYPE html>
<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("button").click(function() {
                $("<h2>Hello world!</h2>").replaceAll("p");
            });
        });
    </script>
</head>

<body>

    <button>Replace all p elements with h2 elements</button><br>

    <p>This is a paragraph.</p>
    <p>This is another paragraph.</p>
    <p>This is another paragraph.</p>

</body>

</html>
Try it Yourself - Copy paste code in Online HTML Editor to see the result

References



Comments