Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace node with innerhtml

With JavaScript I want to remove 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>
like image 710
Mostafa Mahdieh Avatar asked Apr 30 '10 07:04

Mostafa Mahdieh


People also ask

Why you shouldn't use innerHTML?

'innerHTML' Presents a Security Risk The use of innerHTML creates a potential security risk for your website. Malicious users can use cross-site scripting (XSS) to add malicious client-side scripts that steal private user information stored in session cookies.

Can you += innerHTML?

Appending to innerHTML is not supported: Usually, += is used for appending in JavaScript. But on appending to an Html tag using innerHTML, the whole tag is re-parsed.

How do you replace innerHTML?

To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.


2 Answers

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.');
like image 164
gnarf Avatar answered Oct 22 '22 10:10

gnarf


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

http://youmightnotneedjquery.com/#replace_from_html

like image 2
Павел П Avatar answered Oct 22 '22 11:10

Павел П