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

我该怎么做呢?


当前回答

这个问题很老了,但我发现自己在学习微软认证,在学习书上建议使用:

oldElement.replaceNode(newElement)

我查了一下,似乎只有IE支持。哎. .

我想我只是把它添加在这里作为一个有趣的旁注;)

其他回答

通过使用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 a = A.parentNode.replaceChild(document.createElement("span"), A);

a是替换后的a元素。

这是最好的方法。父母不需要。只需使用Element。outerHTML =模板;

// 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>';

替换LI元素的示例

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

你可以使用Node. replacewith (newNode)替换HTML元素或节点。

下面的例子应该保留所有来自源节点的属性和子节点:

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

如果你有这些元素:

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

运行以上代码后,你将得到以下元素:

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