javascript - 无法在javascript中正确更改父元素

标签 javascript html

我有两个 div 元素,在第一个元素中我放了三个按钮。这是代码

它工作正常但问题出在重置按钮(它应该移动所有按钮以启动 div)当我按下它时只会将 2 个元素移回起始 div。什么是问题?

function move(element){
    let newParent = document.querySelector('#favourites');
    newParent.append(element);
  }

function reset(){
    let startingDiv = document.querySelector('#startingArea');  
    let favouritesDiv = document.querySelector("#favourites");

    var children = favouritesDiv.children;

    for(var i=0;i<children.length;i++){
        startingDiv.append(children[i]);
    }
  }
<html>
  <head>
      <script src="script.js"></script>
  </head>

  <body>
    <h1>Click on your favourite wrestler<h1>
    <div id="startingArea">
        <button onclick='move(this)' id="cena1">John Cena</button>
        <button onclick='move(this)' id="cena2">Jooohn Ceenna</button>
        <button onclick='move(this)' id="cena3">JOoOoOOoooOooOOooOohn CeeeeeeEEEnaaaaaaa</button>
    </div>
      <h3>Your Favourite Wrestlers</h3>
      <div id="favourites">
      </div>
      <br><br><br>
      <button onclick="reset()">reset</button>
  </body>

</html>

最佳答案

您可以将以下代码用于重置功能,它应该可以工作:

function reset(){
    let startingDiv = document.querySelector('#startingArea');  
    let favouritesDiv = document.querySelector("#favourites");

    while(favouritesDiv.firstChild) {
        startingDiv.append(favouritesDiv.firstChild);
    }
}

关于javascript - 无法在javascript中正确更改父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50501616/

相关文章:

javascript - 查看数组的子数组是否存在

Javascript:如何在网站上进行拖放操作时设置光标?

jquery - 使用 jQuery 删除动态生成的表行

c# - 删除 block html 标签。小MCE

javascript - 滚动事件在 IE11 中过于不稳定,Chrome 建议提高我的 React 应用程序中的 RAIL 性能

javascript - 比较 js 日期……现在是星期几?

javascript - 使用javascript检测Android设备是手机还是平板电脑

javascript - Electron - 找不到网络路径

javascript - 使用 Javascript 定期动画化数字

python - Jupyter Notebook 导出 HTML 深色