Replace node with innerhtml
8 answers
Try the following:
var oldElem = document.getElementById('t1');
oldElem.innerHTML = 'this is <b> the text </b> I want to remain.';
var parentElem = oldElem.parentNode;
var innerElem;
while (innerElem = oldElem.firstChild)
{
// insert all our children before ourselves.
parentElem.insertBefore(innerElem, oldElem);
}
parentElem.removeChild(oldElem);
There is a demo here.
This is actually the same as .replaceWith()
from jQuery:
$("#t1").replaceWith('this is <b> the text </b> I want to remain.');
+2
a source to share
It works:
var t1 = document.getElementById("t1");
t1.parentNode.innerHTML = t1.innerHTML;
Edit:
Note that if the parent of t1 has other children, the above will also remove all those children. The following issue has been fixed:
var t1 = document.getElementById("t1");
var children = t1.childNodes;
for (var i = 0; i < children.length; i++) {
t1.parentNode.insertBefore(children[i].cloneNode(true), t1);
}
t1.parentNode.removeChild(t1);
+1
a source to share
you might want to consider using jquery if possible. it would make your life wayyyyyyyyyy way easier.
after you have jquery you can easily do this via
$("#t1").html("this is <b> the text </b> I want to remain.");
and if you find it difficult to learn, you can always start by learning about jquery selectors. you don't know why you haven't been using it all the time :)
sorry if this is not what you want exactly.
~ jquery addict
Updated:
To show what html text is placed inside.
0
a source to share
This is similar to the other answers, but more functional.
go.onclick = () => {
[...t1.childNodes].forEach(e => {
t1.parentElement.insertBefore(e, t1);
});
t1.remove();
go.disabled = true;
}
#t1 {
color: red;
}
<div>
<div>BEFORE</div>
<div id="t1">
this is <b> the text </b> I want to remain.
</div>
<div>AFTER</div>
<button id="go">GO</button>
</div>
0
a source to share