Webeng Webeng - 5 months ago 16
Javascript Question

Replacing html content with javascript

Question:

How would I go about replacing an html element and it's content with other content (with javascript)?

Elaborating on what I mean:

If I have the following html code:

<div id="container">
<div id="one" class="element">some text</div>
<div id="two" class="element">some text</div>
<div id="three" class="element">some text</div>
<div id="four" class="element">some text</div>
</div>


and I wanted to replace
<div id="two" class="element">some text</div>
with

<div id="a" class="element">some text</div>
<div id="b" class="element">some text</div>


to have the following result:

<div id="container">
<div id="one" class="element">some text</div>
<div id="a" class="element">some text</div>
<div id="b" class="element">some text</div>
<div id="three" class="element">some text</div>
<div id="four" class="element">some text</div>
</div>


how might I be able to do with with javascript?
I know that I could do it in a hacky method:

document.getElementById('container').innerHTML =
"<div id='one' class='element'>some text</div>" +
"<div id='a' class='element'>some text</div>" +
"<div id='b' class='element'>some text</div>" +
"<div id='three' class='element'>some text</div>" +
"<div id='four' class='element'>some text</div>";


But instead of having to replace everything just to replace 1 div with 2, I assume there is probably a cleaner way. Any ideas?

Answer

Since you tagged your question with jQuery, I'll assume an answer using jQuery is appropriate.

This is done quite easily with jQuery's replaceWith:

$("#container #two").replaceWith('<div id="a" ...');

See here: http://jsbin.com/dogikikefa/edit?html,js,output


Note you can use an array to pass in multiple pieces of html:

$("#container #two").replaceWith([
    '<div id="a" class="element">some replaced text</div>',
    '<div id="b" class="element">some replaced text</div>'
]);

I personally find that cleaner that the extra parenthesis or string concatenation.

http://jsbin.com/rodesabiru/1/edit?html,js,output