我想替换DOM中的一个元素。 例如,有一个<a>元素,我想用<span>代替。
我该怎么做呢?
我想替换DOM中的一个元素。 例如,有一个<a>元素,我想用<span>代替。
我该怎么做呢?
当前回答
我有一个类似的问题,并找到了这个线程。替换对我不起作用,而且在我的情况下,通过父母是很困难的。Inner Html替换了子元素,这也不是我想要的。使用outerHTML完成了这项工作。希望这能帮助到其他人!
currEl = <div>hello</div>
newElem = <span>Goodbye</span>
currEl.outerHTML = newElem
# currEl = <span>Goodbye</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);
我有一个类似的问题,并找到了这个线程。替换对我不起作用,而且在我的情况下,通过父母是很困难的。Inner Html替换了子元素,这也不是我想要的。使用outerHTML完成了这项工作。希望这能帮助到其他人!
currEl = <div>hello</div>
newElem = <span>Goodbye</span>
currEl.outerHTML = newElem
# currEl = <span>Goodbye</span>
这是最好的方法。父母不需要。只需使用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>';
你可以使用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>
在创建新元素(createElement)后,你可以在目标元素的父元素上使用replaceChild:
const newElement = document.createElement(/*...*/);
const target = document.getElementById("my-table");
target.parentNode.replaceChild(newElement, target);
如果你的新元素的起点是HTML,你可以使用insertAdjacentHTML,然后在父元素上使用removecchild(或者在现代环境中对元素本身进行remove):
const target = document.getElementById("my-table");
target.insertAdjacentHTML("afterend", theHTMLForTheNewElement);
target.parentNode.removeChild(target); // Or: `target.remove()`