Cover Image for jQuery replaceAll() method
85 views

jQuery replaceAll() method

The jQuery replaceAll() method is used to replace matched elements with new content or elements. It removes the matched elements from the DOM and replaces them with the specified content or elements.

Here’s the basic syntax of the replaceAll() method:

newContent.replaceAll(target)

Parameters:

  • newContent: A string, HTML element, or jQuery object representing the new content or elements to be inserted.
  • target: A selector, HTML element, or jQuery object representing the elements that will be replaced by the new content.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery replaceAll() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div class="original">
        <p>This is the original content.</p>
    </div>

    <script>
        $(document).ready(function() {
            // New content to replace the original content
            var newContent = "<h2>This is the new content!</h2>";

            // Replace the original content with the new content
            $(".original").replaceAll(newContent);
        });
    </script>
</body>
</html>

In this example, we have a <div> with the class “original” containing a paragraph element. We use the replaceAll() method to replace the content of the <div> with the new content specified in the newContent variable. As a result, the paragraph element is removed, and the new <h2> element is inserted in its place.

It’s important to note that the replaceAll() method removes the original elements from the DOM, so they will no longer be present after the replacement.

The replaceAll() method is particularly useful when you want to replace specific elements with new content or elements in your web page dynamically. It allows you to perform content manipulation easily and efficiently.

YOU MAY ALSO LIKE...

The Tech Thunder

The Tech Thunder

The Tech Thunder


COMMENTS