我想替换DOM中的一个元素。 例如,有一个<a>元素,我想用<span>代替。
我该怎么做呢?
我想替换DOM中的一个元素。 例如,有一个<a>元素,我想用<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>';
其他回答
通过使用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元素。
我有一个类似的问题,并找到了这个线程。替换对我不起作用,而且在我的情况下,通过父母是很困难的。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);
这是最好的方法。父母不需要。只需使用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>';