Replacing elements in jQuery

replaceWith method

The method replaceWithreplaces the internal content of the element with the new content. It has the following use cases:

  • replaceWith(‘html markup’): replace element content with HTML markup
  • replaceWith(element): replacing the content of an element with some HTML element
  • replaceWith(jQuery): replacing element content with jQuery object
  • replaceWith(function): replace the contents of the element with the object returned by the function

For example, let’s replace the first element of the list with the new content:

$('li.lang').first().replaceWith('<li class="lang">JavaScript</li>');

Let’s use a function to replace the content. Let’s say we have the following markup:

<div id="list">
    <div class="lang">Java</div>
    <div class="lang">C/C++</div>
    <div class="lang">PHP</div>
</div>

But for example, we wanted to convert this div element into a list. Then we can write like this:

$('div.lang').replaceWith(function() {
        return '<li class="lang">'+$(this).text()+"</li>";
});
$('div#list').replaceWith(function() {
        return '<ol>'+$(this).html()+"</ol>";
});

The function iterates over all elements of the sample. We can get the element to be iterated using the keyword this. Then we replace the elements inside the div with list elements. As a result, we get the following markup:

<ol>
    <li class="lang">Java</li>
    <li class="lang">C/C++</li>
    <li class="lang">PHP</li>
</ol>

replaceAll method

The method replaceAll(replaced_element)replaces all the elements specified in the parameter with the new element. We can pass a selector, an HTML element, or a jQuery object as the element to be replaced. For example, let’s replace all the elements of the previous list with other content:

$('<li class="lang">List item</li>').replaceAll('li.lang');

This will result in the following markup:

<ol>
    <li class="lang">List item</li>
    <li class="lang">List item</li>
    <li class="lang">List item</li>
</ol>