Chcę zamienić element w DOM.
Na przykład istnieje <a>element, który chcę zastąpić <span>zamiast niego.
Jak bym to zrobił?
Chcę zamienić element w DOM.
Na przykład istnieje <a>element, który chcę zastąpić <span>zamiast niego.
Jak bym to zrobił?
Odpowiedzi:
używając 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 jest zastąpionym elementem A.
A.replaceWith(span) - Nie potrzeba żadnego rodzicaFormularz ogólny:
target.replaceWith(element);
O wiele lepszy / czystszy niż poprzednia metoda.
W Twoim przypadku użycia:
A.replaceWith(span);
Obsługiwane przeglądarki - 94% kwiecień 2020
Miałem podobny problem i znalazłem ten wątek. Wymiana nie działała dla mnie, a wyjazd przez rodzica był trudny w mojej sytuacji. Inner Html zastąpił dzieci, co też nie było tym, czego chciałem. Korzystanie z externalHTML wykonało zadanie. Mam nadzieję, że to pomoże komuś innemu!
currEl = <div>hello</div>
newElem = <span>Goodbye</span>
currEl.outerHTML = newElem
# currEl = <span>Goodbye</span>
Możesz zamienić węzeł za pomocą Node.replaceWith(newNode).
Ten przykład powinien zachować wszystkie atrybuty i elementy podrzędne z węzła źródłowego:
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)
})
Biorąc pod uwagę już proponowane opcje, najłatwiejsze rozwiązanie bez znalezienia rodzica:
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);
target.replaceWith(element);to nowoczesny (ES5 +) sposób na zrobienie tego