Cover Image for jQuery replaceWith() method
98 views

jQuery replaceWith() method

The jQuery replaceWith() method is used to replace one or more 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 replaceWith() method:

$(selector).replaceWith(newContent)

Parameters:

  • selector: A selector string or jQuery object representing the element(s) to be replaced.
  • newContent: A string, HTML element, or jQuery object representing the new content or elements that will replace the selected elements.

Example:

<!DOCTYPE html>
<html>
<head>
    <title>jQuery replaceWith() Method Example</title>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
    <div id="myDiv">
        <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
            $("#myDiv").replaceWith(newContent);
        });
    </script>
</body>
</html>

In this example, we have a <div> with the ID “myDiv” containing a paragraph element. We use the replaceWith() method to replace the entire 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 replaceWith() method removes the original elements from the DOM, so they will no longer be present after the replacement.

The replaceWith() method is particularly useful when you want to replace specific elements with new content or elements 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