繁体   English   中英

如何使用 Javascript 替换 DOM 元素?

[英]How to replace DOM element in place using Javascript?

我正在寻找替换 DOM 中的元素。
例如,我想用<span>替换一个<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>

A.replaceWith(span) - 不需要父级

通用形式:

target.replaceWith(element)

比以前的方法更好/更干净。

对于您的用例:

A.replaceWith(span)

高级用法

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

例子:

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

安全处理null目标

如果您的目标有机会为空,您可以考虑使用新的?. 可选链操作符。 如果目标不存在,则不会发生任何事情。 在这里阅读更多。

target?.replaceWith(element)

相关 DOM 方法

  1. 阅读更多- child.beforechild.after
  2. 阅读更多- parent.prependparent.append

Mozilla 文档

支持的浏览器- 95% 21 年 10 月

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

a 是被替换的 A 元素。

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

oldElement.replaceNode(newElement)

我查了一下,好像只支持IE。 呵呵..

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

我有一个类似的问题,并找到了这个线程。 Replace 对我不起作用,而且对我的情况来说,去父母身边很困难。 内部 Html 替换了孩子,这也不是我想要的。 使用outerHTML 完成了工作。 希望这对其他人有帮助!

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

您可以使用Node.replaceWith(newNode)替换HTML ElementNode

此示例应保留原始节点的所有属性和子项:

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>

创建新元素 ( createElement ) 后,您可以在目标元素的父元素上使用replaceChild

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

如果新元素的起点是 HTML,则可以在父元素上使用insertAdjacentHTMLremoveChild (或在现代环境中remove元素本身):

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

最好的方法来做到这一点。 不需要父母。 只需使用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>';

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

鉴于已经提出的选项,无需找到父级的最简单解决方案:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM