正在尝试删除子元素的最后一个子元素

Trying to removing last child of a child element

本文关键字:元素 最后一个 删除      更新时间:2023-09-26

试图删除"leftSideImages"的最后一个子项,以便右侧的图像比左侧的图像少一个。下面是我的代码。目标是将左边的图像克隆到右边减去一的图像上。非常感谢。

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>Matching Game</title>
    <style>
        div {
            position: absolute;
            width: 500px;
            height: 500px
        }
        img { 
            position: absolute
        }
        #rightSide { 
            left: 500px; 
            border-left: 1px solid black 
        }
    </style>
    <script>
        function generateFaces(){
            var numberOfFaces = 5;
            var theLeftSide = document.getElementById("leftSide");
            var theRightSide = document.getElementById("rightSide");
            for ( var i = 0; i< numberOfFaces; i++){
                var random_top = Math.floor(Math.random() * 400);
                var random_left = Math.floor(Math.random() * 400);
                var img = document.createElement("img");
                img.src="smile.png";
                img.style.top = random_top + "px";
                img.style.left = random_left + "px";

                theLeftSide.appendChild(img);
            }
            var leftSideImages = theLeftSide.cloneNode(true);
            //this doesn't work         leftSideImages.removeChild(theLeftSide.lastChild);
            // it gets rid of everything.
            // I'm trying to clone the left side onto the right with one less image
            theRightSide.appendChild(leftSideImages);
        }
    </script>
  </head>
  <body>
      <h3>Matching Game</h3>
      <p>Click on the extra smiling face on the left.</p>
      <div id="leftSide"></div>
      <div id="rightSide"></div>
      <script>generateFaces()</script>
  </body>
</html>

您需要使用removeChildlastElementChild,如下所示:

var parent = document.getElementById("leftSide");
parent.removeChild(parent.lastElementChild);
<div id="leftSide">
  <div>1</div>
  <div>2</div>
  <div>3</div>
</div>

您正试图删除与调用removeChild的元素不同的元素的子元素。它应该是:

leftSideImages.removeChild(leftSideImages.lastChild);

我不知道为什么你的代码删除了所有内容。根据文档,如果参数不是给定父级的子级,它应该抛出异常。

原因是您正在克隆整个左侧,然后删除最后一个子项,即整个左侧,

  var leftSideImages = theLeftSide.cloneNode(true);
  //leftSideImages now has whole theLeftSide - the div not its content.
  var i,l, children;
  children = theLeftSide.childNodes;
  i=0;
  l = children.length;
  for( i; i< l ; i++){
    theRightSide.appendChild(children[i].cloneNode(true));
  }
  theRightSide.removeChild(theRightSide.lastChild);

请记住,可能有更好的解决方案。

这是小提琴,向你展示它的作用。

https://jsfiddle.net/f0hrre90/

使用leftSideImages.removeChild(leftSideImages.lastChild);而不是leftSideImages.removeChild(theLeftSide.lastChild);

这是正确的,已经给了一个朋友。:-)我也在我的机器上运行过同样的东西。