如何删除最后(动态)创建的元素?

时间:2018-07-13 21:01:28

标签: javascript html css frontend

所以,我有2个功能,

第一个创建10个元素:

    function addDay() {
           // For loop to create 10 div elements. 
           for (k = 1; k < 11; k++) {     
           let div = document.createElement("div");
           div.setAttribute("class", "studentGrades")
           div.className += " sgID" + k
           div.setAttribute("onclick", "userInput(this, Number(prompt('Please, enter 
    number here')))");
           div.innerHTML = "0"
           document.querySelector("#container3").appendChild(div)
           }}

第二个用于删除以前生成的元素(div):

 function removeDay() {
 // Looping through all 10 div elements to delete them.
 for (let j = 0; j < 10; j++) {
    let removeDay = document.querySelector('.studentGrades');
    removeDay.parentNode.removeChild(removeDay);
}}

这些功能代表按钮(添加日期)和(删除日期)

这是问题所在,可以单击Button(例如,单击10次),这将创建10列,每列包含10个div元素,我希望我的removeDay函数删除最后一列,现在它执行与删除操作完全相反的操作首先创建的列。

4 个答案:

答案 0 :(得分:2)

问题是此行返回第一个元素:

let removeDay = document.querySelector('.studentGrades');

您可以使用以下命令获取最后一个元素

let removeDay = document.querySelector('.studentGrades:last-child');

但是,不需要多次致电document.querySelector。相反,您可以使用Node.lastChild直接访问容器的最后一个元素:

const container = document.getElementById('container');
const add = document.getElementById('add');
const remove = document.getElementById('remove');

let index = -1;

add.onclick = () => {
  // Add 10 new elements at the end:
  
  const newLastIndex = index + 10;
  
  while (index < newLastIndex) {     
    let div = document.createElement('div');

    div.className = 'studentGrades';
    div.innerHTML = ++index;

    container.appendChild(div);
  }
  
  remove.disabled = false;
};

remove.onclick = () => {
   // Remove last 10 elements:
   
   for (let i = 0; i < 10; ++i) {
      container.removeChild(container.lastChild);
      
      // This will not work in IE:
      // container.lastChild.remove();
  }
  
  index -= 10;
  
  if (index === -1) {
    remove.disabled = true;
  }
};
body,
button {
  font-family: monospace;
}

#container {
  position: relative;
  border: 3px solid black;
  border-right: none;
  margin-bottom: 10px;
}

#container:empty {
  border-top: none;
}

.studentGrades {
  position: relative;
  border-right: 3px solid black;
  width: 10%;
  box-sizing: border-box;
  display: inline-block;
  text-align: right;
  padding: 5px;
}
<div id="container"></div>

<button id="add">ADD</button>
<button id="remove" disabled>REMOVE</button>

如果您不需要支持IE,则可以使用Node.removeChild()

container.removeChild(container.lastChild);

您可以使用ChildNode.remove()并执行以下操作:

container.lastChild.remove();

答案 1 :(得分:1)

document.querySelector() 仅找到第一个匹配项

请尝试使用: document.querySelector('.studentGrades:last-child')

答案 2 :(得分:0)

也许是这样的:

In [41]: i, j, data = zip(*((i, t[0], t[1]) for i, row in enumerate(alist) for t in row))

In [43]: coo_matrix((data, (i, j)), shape=(2, 4))
 function addDay() {
   for (k = 1; k < 11; k++) {
      let div = document.createElement("div");
      div.setAttribute("class", "studentGrades");
      div.className += " sgID" + k;
      div.setAttribute("onclick", "userInput(this, Number(prompt('Please, enter number here')))");
      div.innerHTML = "0";
      document.querySelector("#container3").appendChild(div)
   }
}

function removeDay() {
    for (let j = 0; j < 10; j++){
    	if(document.querySelectorAll(".studentGrades:last-child").length){
    	  document.querySelectorAll(".studentGrades:last-child")[0].remove();
    	}
    }
}

答案 3 :(得分:0)

您可以这样创建一个堆栈:

function Stack() {
    let items = [];
    let maxIndex = -1;

    this.isEmpty = () => {
        return maxIndex === -1;
    };

    this.push = (item) => {
        (items.length > ++maxIndex) ? (items[maxIndex] = item) : items.push(item);
    };

    this.pop = () => {
        return (maxIndex >= 0) ? items[maxIndex--] : undefined;
    };

    this.top = () => {
        return (maxIndex >= 0) ? items[maxIndex] : undefined;
    }
}

,然后在添加div时推送项目:

function addDay(S) {
       // For loop to create 10 div elements. 
       for (k = 1; k < 11; k++) {     
       let div = document.createElement("div");
       div.setAttribute("class", "studentGrades")
       div.className += " sgID" + k
       div.setAttribute("onclick", "userInput(this, Number(prompt('Please, enter 
number here')))");
       div.innerHTML = "0";
       document.querySelector("#container3").appendChild(div);
       S.push(div);
       }}

并在删除项目时弹出,这里我们只是从堆栈中删除所有元素:

function removeDay(S) {
 var itemToRemove;
 while (itemToRemove = S.pop()) itemToRemove.remove();
}}

自然地,您将需要以某种方式创建堆栈,例如:

let S = new Stack();