1

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?

6
  • Did you try anything at all? Any documentation? Library? Commented Jun 12, 2016 at 18:28
  • @Amit at the bottom part of my question, I showed what I tried but the method was hacky and not ideal Commented Jun 12, 2016 at 18:29
  • Did you try reading jquery's documentation? Commented Jun 12, 2016 at 18:30
  • @Amit yes I did, but we don't always find what we are seeking. jszobody answered the question well though Commented Jun 12, 2016 at 18:33
  • It just doesn't seem you really tried to answer your own question - but perhaps I'm wrong. You should improve your searching skills though.. this is very basic and simple to find (there are other very common ways to do this as you see..) and knowing how to find what you need is crucial these days. Good luck! Commented Jun 12, 2016 at 18:39

3 Answers 3

4

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

Sign up to request clarification or add additional context in comments.

Comments

3

You could use replaceWith

$('#button').click(function(){
    $("#container #two").replaceWith( 
        ('<div id="a" class="element">some text</div>'),
           ('<div id="b" class="element">some text</div>') );
});

2 Comments

might I ask why you included an extra parenthesis? does it add a benefit? : replaceWith( (...) )
@Webeng: When you want to add multiple dom elements, it would be cleaner... Look at my updated answer
3

Vanilla JS

var div_two = document.getElementById('two');

// Create Div A
var div_a = document.createElement('div');
div_a.appendChild( document.createTextNode('some text a') );
div_a.setAttribute('id','a');
div_a.className = 'element';

// Create Div B
var div_b = document.createElement('div');
div_b.appendChild( document.createTextNode('some text b') );
div_b.setAttribute('id','b');
div_b.className = 'element';

// Where replacement occurs
var parent = div_two.parentNode;
parent.replaceChild(div_b, div_two);  // Replace Two with B
parent.insertBefore(div_a, div_b);    // Insert A before B
<div id="container">
    <div id="one" class="element">some text one</div>
    <div id="two" class="element">some text two</div>
    <div id="three" class="element">some text three</div>
    <div id="four" class="element">some text four</div>
</div>

jQuery will certainly save you more lines of code, so if you're already using it you could do so here -- see other answers -- but understanding what jQuery is saving you from doing is important (ergo learn the Vanilla first)

Automating

This demonstrates how to create any number of elements, by just populating the ['a','b','c','d'] array. If you wanted different text or other elements, you could easily create an object (hash table) to pull from ({ "a": { "textContent": "This is some value for this id" } }). Ideally this could be stored in a database; though if you're loading your front-end that way, you may want to look into other languages like Angular or React.

var target = document.getElementById('two'),
    parent = target.parentNode;

// Create elements
var new_divs = [];
['a','b','c','d'].forEach(id=>{
   let new_div = document.createElement('div');
   new_div.setAttribute('id', id);
   new_div.className   = 'element';
   new_div.textContent = 'some text ' + id;
  
   new_divs.unshift( new_div );
});


// Add to page
new_divs.forEach((div,pass)=>{
   if (pass==0)
     parent.replaceChild( div, target );  // first pass replace
   else
     parent.insertBefore( div, target );  // all others insert before the last
  
   target = div;
});
<div id="container">
    <div id="one" class="element">some text one</div>
    <div id="two" class="element">some text two</div>
    <div id="three" class="element">some text three</div>
    <div id="four" class="element">some text four</div>
</div>

jQuery will certainly save you more lines of code, so if you're already using it you could do so here -- see other answers -- but understanding what jQuery is saving you from doing is important (ergo learn the Vanilla first)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.