我想替换DOM中的一个元素。 例如,有一个<a>元素,我想用<span>代替。

我该怎么做呢?


当前回答

考虑到已经提出的选项,最简单的解决方案是不找父母:

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

其他回答

A.replaceWith(span) -不需要父元素

通用的形式:

target.replaceWith(element)

比以前的方法好/干净多了。

对于您的用例:

A.replaceWith(span)

高级用法

您可以传递多个值(或使用展开运算符…)。 任何字符串值都将作为文本元素添加。

例子:

// 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]

安全处理空目标

如果目标有可能为空,则可以考虑使用newish ?。可选的连接操作符。如果目标不存在,什么都不会发生。点击这里阅读更多。

target?.replaceWith?.(element)

相关DOM方法

阅读更多——孩子。之前和孩子,之后 阅读更多——父母。Prepend和parent.append

Mozilla文档

支持的浏览器- 97% 11月22日

我有一个类似的问题,并找到了这个线程。替换对我不起作用,而且在我的情况下,通过父母是很困难的。Inner Html替换了子元素,这也不是我想要的。使用outerHTML完成了这项工作。希望这能帮助到其他人!

currEl = <div>hello</div>
newElem = <span>Goodbye</span>
currEl.outerHTML = newElem
# currEl = <span>Goodbye</span>
var a = A.parentNode.replaceChild(document.createElement("span"), A);

a是替换后的a元素。

通过使用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>

考虑到已经提出的选项,最简单的解决方案是不找父母:

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