How to replace DOM element in place using Javascri

2019-01-02 20:05发布

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?

5条回答
刘海飞了
2楼-- · 2019-01-02 20:45
var a = A.parentNode.replaceChild(document.createElement("span"), A);

a is the replaced A element.

查看更多
看淡一切
3楼-- · 2019-01-02 20:52

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 ;)

查看更多
高级女魔头
4楼-- · 2019-01-02 20:58

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);

Mozilla Docs

Supported Browsers - 86% Nov 2018

查看更多
几人难应
5楼-- · 2019-01-02 21:11

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>
查看更多
与风俱净
6楼-- · 2019-01-02 21:12

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);
    }
}
查看更多
登录 后发表回答