Home > Enterprise >  Replacing divs with vanilla javascript
Replacing divs with vanilla javascript

Time:03-21

I'm looking for a way to replace child element, in the code below, I'm trying to replace child-div-1 by child-div-2, then child-div-2 by child-div-3, then 3 by 1 etc, looping while I click on a button. (This code is an example, in my actual code inside the parent-div there is 4 others divs with 1 span element in each..)

edit : only one "parent-div" at a time, the other ones are on display:none.

HTML CODE EXAMPLE:

    <button onclick="replaceContent()"></button>

<div >
            <div id="child-div-1">
                <span>hello</span>
            </div>
        </div>
<div >
                <div id="child-div-2">
                    <span>world</span>
                </div>
            </div>
<div >
                <div id="child-div-3">
                    <span>test</span>
                </div>
            </div>

JAVASCRIPT ideas & tests :

let parentDiv = document.getElementByClassName('parent-div');
let childOne = document.getElementById('child-div-1');
let childTwo = document.getElementById('child-div-2');
let childThree = document.getElementById('child-div-3');

function replaceContent() {
then I am stuck here;
}

I don't know how to setup this : replaceChild(newChild, oldChild);

Thank you for your help !

CodePudding user response:

use the flex order property

var cnt = 0;
function replaceContent(){
    if( (cnt % 2) == 0) document.getElementById("child-div-1").style.order=2;
    else document.getElementById("child-div-1").style.order=0;
    cnt  ;    
}
.parent-div{
  display:flex;
  flex-direction:column;
  }
<button onclick="replaceContent()"></button>

<div >
  <div id="child-div-1">
    <span>hello</span>
  </div>


  <div id="child-div-2">
    <span>world</span>
  </div>


  <div id="child-div-3">
    <span>test</span>
  </div>
</div>

CodePudding user response:

var parents = document.getElementsByClassName('parent-div');
var cnt = 0;

function replaceContent(){
var idx = cnt % 3
parents[idx].classList.remove("show");
parents[idx].classList.add("hide");
idx = (idx   1) % 3
parents[idx].classList.remove("hide");
parents[idx].classList.add("show");
cnt  

}
.show {
   display:block;
  }
  
 .hide{
 display:none;
 }
<button onclick="replaceContent()"></button>

<div >
  <div id="child-div">
    <span>hello</span>
  </div>
</div>

<div >
  <div id="child-div">
    <span>world</span>
  </div>
</div>
<div >
  <div id="child-div">
    <span>test</span>
  </div>
</div>

  • Related