Categories
JavaScript

JavaScript replaceWith – how to use it

I remember the time when JavaScript was not this good. We had to use libraries and frameworks, like jQuery, to do some basic stuff much easier. I remember the time when JavaScript replaceWith – like functions and methods were just a dream.

There are times when we need to remove one element and replace it with another one. I will show two of the most common ways.

<div id="parent">
    <div id="child"></div>
</div>

<script>
    /**
     * First way we can replace one element with another is by changing .innerHTML of a parent element
    **/
    
    document.querySelector("#parent").innerHTML = `<div id="another-child"></div>`;
    
    //Result
    /*
        <div id="parent">
            <div id="another-child"></div>
        </div>
    */
    
    /**
     * Another way is by removing child add adding another child using createElement
    **/
    
    let parent = document.querySelector("#parent");
    let oldChild = document.querySelector("#child");
    let newChild = document.createElement("div");
    newChild.setAttribute("id", "another-child");
    parent.removeChild(oldChild);
    parent.appendChild(newChild);
    //Result
    /*
        <div id="parent">
            <div id="another-child"></div>
        </div>
    */
    
</script>

Here is where JavaScript comes to the rescue with the replaceWith() method. According to MDN: The Element.replaceWith() method replaces this Element in the children list of its parent with a set of Node or DOMString objects. DOMString objects are inserted as equivalent Text nodes.

This means that we can use createElement method to create a new element(s), but if we use DOMString, JavaScript will interpret it as text, not as an element node.

<div id="parent">
    <div id="child"></div>
</div>

<script>
//Let's create element using createElement method
    let parent = document.querySelector("#parent");
    let oldChild = document.querySelector("#child");
    let newChild = document.createElement("div");
    newChild.setAttribute("id", "another-child");
    oldChild.replaceWith(newChild);
    //Result
    /*
        <div id="parent">
            <div id="another-child"></div>
        </div>
    */
    
    let parent = document.querySelector("#parent");
    let oldChild = document.querySelector("#child");
    let newChild = `<div id="another-child"></div>`;
    oldChild.replaceWith(newChild);
    
    //Result
    /*
        <div id="parent">
            This is shown as text in browser -> <div id="another-child"></div>
        </div>
    */
</script>

If you have any questions or anything you can find me on my Twitter, or you can read some of the older articles like Handling HTML form security