JQuery replacewith() usage with examples

The majority of the time, jQuery is being used to attach click event handlers to DOM elements, which is OK. jQuery is so useful in this situation that it’s difficult to justify against using it to handle and delegate events. However, be prepared that other tasks will arise, and some of them may become pretty messy. Replacing one DOM element with another is one example. While this may appear to be a simple task, it can quickly become difficult when working with vanilla JavaScript. Normally, it is advised that learning how to perform things using vanilla JavaScript that you could do with jQuery, but there are occasions when rebuilding the wheel is a bad idea.

This is where the jQuery replaceWith() method comes in handy; it lets you cut out a section of the page and replace it with another. Simply specify the original DOM area as well as the new piece, and jQuery will take care of the rest. The expressive syntax is what makes this function so useful; at a high level, it’s as simple as A.replaceWith (B). You have to hand it to the jQuery group for putting so much abstraction into one single method. If you don’t trust me, test it for yourself with only vanilla JavaScript. I believe you will find it to be somewhat boring.

What is Jquery replacewith() method?

Replacing text in a string is a simple and straightforward process. The replaceWith() method replaces a collection of Node or DOMString objects for a node in its parent’s children collection. Text nodes are equal to DOMString objects. One child element is replaced with another child element in this case.

Syntax of Jquery replacewith():

<!DOCTYPE html>
<html>
    <head>
        <meta charset="utf-8">
        <title>jQuery replaceWith() Example</title>
        <script language="javascript"  src="http://code.jquery.com/jquery-1.4.2.min.js"></script>
    </head>
        <script id="demo" type="text/javascript">
            $(document).ready(function() {
                $("#foo").click(function(){
                    $(this).replaceWith("<ul><li>one</li><li>two</li><li>three</li></ul>");
                });
            });
        </script>
    <body>
    <div id="foo">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla at lectus erat.</div>
    </body>
</html>
  • We fetch the element using its id in the function (document.getElementById(“id_b”));
  • After that, we’ll build a new element (document.createElement(“u”);), which will result in underlined text.
  • We then add content to the newly generated element by constructing a new element (document.createTextNode(“New info”);).
  • The new content will be added to the newly constructed element (new elem.appendChild(new_info);).
  • Finally, the old element is replaced by the newly constructed element (old elem.replaceWith(new element);).

Difference between replacewith() and replaceall():

The replaceAll(selector) method replaces all elements that match the provided selector with the elements that match.

Replacewith(content) replaces matching items with the provided HTML or DOM elements. This yields the jQuery element that has been deleted from the DOM after being replaced.

Difference between replace() and replaceall():

The replace() function replaces all instances of old char with new char, but the replaceAll() method replaces all instances of existing string with new string. Essentially, replace() replaces characters, while replaceAll() replaces parts of strings.

The calling String object is not changed by the Javascript replace() method. It just creates a new string. Include the g switch in the regular expression to run a global search and replace. It also return a value.

Replace() method consists of:

There are two parameters include the replace() method.

  • The searchvalue parameter is necessary, and it specifies the value or regular expression that will be replaced with the new value.
  • The newvalue option is needed, and it is the value that will be used to replace the search value.

Example:

const source = "abcdefabcdef";
const str1 = "abc", str2 = "xyz";
const reg1 = /abc/g, reg2 = "xyz";

Case 1 : When we want to replace a string by another

We’ve added an event handler to the element with the id: “foo” in the example. When that element is selected, it is replaced and removed from the page with markup specified in a string. Yes, it’s that simple, and you can do a lot more exciting things with this jQuery function.

Additional Notes:

The replaceWith() method replaces a collection of Node or DOMString objects for a node in its parent’s children listing. Text nodes are equal to DOMString objects. One child element is changed with another child element in this case.

• The.replaceWith() method clears any event handlers and data connected with the nodes that have been eliminated.

• Before jQuery 1.9, if the initial node in the current jQuery set was not attached to a document,.replaceWith() would attempt to add or edit nodes in the current jQuery set, returning a new jQuery set rather than the existing set. Depending on the number and connectedness of its parameters, the method may or may not have provided a new result! .after(),.before(), and.replaceWith() all return the old unmodified set as of jQuery 1.9. Attempting to utilize these functions on a node without a parent has no effect, meaning that neither the set nor the nodes it includes are altered.

<b id="id_b">Number of examples</b>
<button onclick="function_name()">Press Me</button>
 <script>
 function function_name()
 {
  var old_elem = document.getElementById("id_b");
  var new_element = document.createElement("u");
  var new_content = document.createTextNode("New Info");
  new_elem.appendChild(new_info); 
  old_elem.replaceWith(new_element);
 }
</script>

Example Explanation

  • In the above example, id(id_b) is used to create bold text.
  • The javascript function is called when the button is clicked.

console.log(source.split(str1).join(str2));

console.log(source.replace(new RegExp(str1,”g”),str2));

//versus

console.log(source.replaceAll(str1,str2));

//Case 2 : When we want to use a regular expression

console.log(source.replace(reg1,reg2));

//versus

console.log(source.replaceAll(reg1,reg2));

//Result = “xyzdefxyzdef”

Conclusion:

Javascript with its exciting features is a wonderful language to build your site’s interface. The jQuery replaceWith() method makes replacing one section of the page with another piece of HTML simple. The syntax is simple, and there are a lot of options if you’re already familiar with jQuery. Here’s a great platform for you to learn JavaScript basics if you want to. Keep connected to learn more.