How to replace DOM element in place using Javascript?

JavascriptDom

Javascript Problem Overview


I am looking to replace an element in the DOM.
For example, there is an <a> element that I want to replace with a <span> instead.

How would I go and do that?

Javascript Solutions


Solution 1 - Javascript

by using replaceChild():

<html>
<head>
</head>
<body>
  <div>
    <a id="myAnchor" href="http://www.stackoverflow.com">StackOverflow</a>
  </div>
<script type="text/JavaScript">
  var myAnchor = document.getElementById("myAnchor");
  var mySpan = document.createElement("span");
  mySpan.innerHTML = "replaced anchor!";
  myAnchor.parentNode.replaceChild(mySpan, myAnchor);
</script>
</body>
</html>

Solution 2 - Javascript

A.replaceWith(span) - No parent needed

Generic form:

target.replaceWith(element)

Way better/cleaner than the previous method.

For your use case:

A.replaceWith(span)

Advanced usage

  1. You can pass multiple values (or use spread operator ...).
  2. Any string value will be added as a text element.

Examples:

// Initially [child1, target, child3]

target.replaceWith(span, "foo")     // [child1, span, "foo", child3]

const list = ["bar", span]
target.replaceWith(...list, "fizz")  // [child1, "bar", span, "fizz", child3]
Safely handling null target

If your target has a chance to be null, you can consider using the newish ?. optional chaining operator. Nothing will happen if target doesn't exist. Read more here.

target?.replaceWith?.(element)
  1. Read More - child.before and child.after
  2. Read More - parent.prepend and parent.append

Mozilla Docs

Supported Browsers - 96% Feb '22

Solution 3 - Javascript

var a = A.parentNode.replaceChild(document.createElement("span"), A);

a is the replaced A element.

Solution 4 - Javascript

This question is very old, but I found myself studying for a Microsoft Certification, and in the study book it was suggested to use:

oldElement.replaceNode(newElement)

I looked it up and it seems to only be supported in IE. Doh..

I thought I'd just add it here as a funny side note ;)

Solution 5 - Javascript

I had a similar issue and found this thread. Replace didn't work for me, and going by the parent was difficult for my situation. Inner Html replaced the children, which wasn't what I wanted either. Using outerHTML got the job done. Hope this helps someone else!

currEl = <div>hello</div>
newElem = <span>Goodbye</span>
currEl.outerHTML = newElem
# currEl = <span>Goodbye</span>

Solution 6 - Javascript

You can replace an HTML Element or Node using Node.replaceWith(newNode).

This example should keep all attributes and childs from origin node:

const links = document.querySelectorAll('a')

links.forEach(link => {
  const replacement = document.createElement('span')
  
  // copy attributes
  for (let i = 0; i < link.attributes.length; i++) {
     const attr = link.attributes[i]
     replacement.setAttribute(attr.name, attr.value)
  }
  
  // copy content
  replacement.innerHTML = link.innerHTML
  
  // or you can use appendChild instead
  // link.childNodes.forEach(node => replacement.appendChild(node))

  link.replaceWith(replacement)
})

If you have these elements:

<a href="#link-1">Link 1</a>
<a href="#link-2">Link 2</a>
<a href="#link-3">Link 3</a>
<a href="#link-4">Link 4</a>

After running above codes, you will end up with these elements:

<span href="#link-1">Link 1</span>
<span href="#link-2">Link 2</span>
<span href="#link-3">Link 3</span>
<span href="#link-4">Link 4</span>

Solution 7 - Javascript

You can use replaceChild on the parent of the target element after creating your new element (createElement):

const newElement = document.createElement(/*...*/);
const target = document.getElementById("my-table");
target.parentNode.replaceChild(newElement, target);

If your starting point for the new element is HTML, you can use insertAdjacentHTML and then removeChild on the parent (or remove on the element itself, in modern environments):

const target = document.getElementById("my-table");
target.insertAdjacentHTML("afterend", theHTMLForTheNewElement);
target.parentNode.removeChild(target); // Or: `target.remove()`

Solution 8 - Javascript

Best way to do it. No parents need. Just use Element.outerHTML = template;

// Get the current element
var currentNode = document.querySelector('#greeting');

// Replace the element
currentNode.outerHTML =
	'<div id="salutations">' +
		'<h1>Hi, universe!</h1>' +
		'<p>The sun is always shining!</p>' +
	'</div>';

Solution 9 - Javascript

Example for replacing LI elements

function (element) {
    let li = element.parentElement;
    let ul = li.parentNode;   
    if (li.nextSibling.nodeName === 'LI') {
        let li_replaced = ul.replaceChild(li, li.nextSibling);
        ul.insertBefore(li_replaced, li);
    }
}

Solution 10 - Javascript

Given the already proposed options the easiest solution without finding a parent:

var parent = document.createElement("div");
var child = parent.appendChild(document.createElement("a"));
var span = document.createElement("span");

// for IE
if("replaceNode" in child)
  child.replaceNode(span);

// for other browsers
if("replaceWith" in child)
  child.replaceWith(span);

console.log(parent.outerHTML);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionomgView Question on Stackoverflow
Solution 1 - JavascriptBjornView Answer on Stackoverflow
Solution 2 - JavascriptGiboltView Answer on Stackoverflow
Solution 3 - JavascriptKamareyView Answer on Stackoverflow
Solution 4 - JavascriptZeliaxView Answer on Stackoverflow
Solution 5 - JavascriptSeanView Answer on Stackoverflow
Solution 6 - JavascriptNurul HudaView Answer on Stackoverflow
Solution 7 - JavascriptT.J. CrowderView Answer on Stackoverflow
Solution 8 - JavascriptVitoldView Answer on Stackoverflow
Solution 9 - JavascriptKirillView Answer on Stackoverflow
Solution 10 - JavascriptSquatterView Answer on Stackoverflow