用香草替换 div javascript

Replacing divs with vanilla javascript

我正在寻找一种方法来替换子元素,在下面的代码中,我试图替换子元素div -1 by child-div-2,然后 child-div-2 by child-div-3,然后 3 by 1 etc,在我点击时循环一个按钮。 (此代码是一个示例,在我的实际代码中,parent-div 中还有 4 个 divs,每个中有 1 个 span 元素。)

编辑:一次只有一个“parent-div”,其他的在 display:none.

HTML 代码示例:

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

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

JAVASCRIPT 想法和测试:

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

我不知道如何设置: replaceChild(newChild, oldChild);

感谢您的帮助!

使用弹性订单属性

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 class="parent-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>

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 class="parent-div">
  <div id="child-div">
    <span>hello</span>
  </div>
</div>

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