开发者

Replace node with innerhtml

With JavaScript I want to remov开发者_Python百科e a specific DOM node and replace it with the innerHTML. For example I want to change

<div>
...
   <div id="t1">
        this is <b> the text </b> I want to remain.
   </div>
...
</div>

To

<div>
...
    this is <b> the text </b> I want to remain.
...
</div>


Try this:

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 effectively the same thing as .replaceWith() from jQuery:

$("#t1").replaceWith('this is <b> the text </b> I want to remain.');


var t1 = document.getElementById("t1"); t1.outerHTML = "this is <b> the text </b> I want to remain.";

http://youmightnotneedjquery.com/#replace_from_html


If you are using jQuery, you can try

var inner = j$("#t1").html()
$('#t1').replaceWith(inner);


This works:

var t1 = document.getElementById("t1");
t1.parentNode.innerHTML = t1.innerHTML;

Edit:

Please note that if the parent of t1 has any other children, the above will remove all those children too. The following fixes this problem:

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


It's very easy actually:

let span = document.getElementById('id');
span.outerHTML = span.innerHTML;


I just modified the HTML Like this.

<div>
<div id="t0">
<div id="t1">
        this is <b> the text </b> I want to remain.
</div>
</div>
</div>

And you do something like

document.getElementById("t0").innerHTML = "this is <b> the text </b> I want to remain.";

Hope it works


you might want to consider using jquery if that's possible. it would make your life way way wayyyyyyyy easier.

once 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 a hassle to learn, you can always start by learning the jquery selectors. you wouldn't know why you haven't been using it all this while :)

sorry if this is not what you want exactly..

~jquery addict

Updated:

To show what html text to put inside.


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜