简体   繁体   English

从 DOM 中删除元素

[英]Remove element from the DOM

I am facing a problem within JavaScript when I attempt to delete a li , it will delete the entire ul .当我尝试删除li时,我在 JavaScript 中遇到了一个问题,它将删除整个ul Does anyone know a solution for this?有谁知道解决方案?

 const add = document.querySelector(".add"); add.addEventListener("click", function() { const cont = document.querySelector(".menu"); const input = document.querySelector(".put"); const newli = document.createElement("LI"); const text = document.createTextNode(input.value); cont.append(newli); newli.appendChild(text); }) const remove = document.querySelector(".remove"); remove.addEventListener("click", function() { const df = document.querySelector(".menu"); df.remove(newli); })
 <div class="parent-row"> <h1>Add a new Post </h1> <div> <input type="text" class="put"> <button class="add">Add a Post</button> <button class="remove">Remove a Post</button> </div> <ul class="menu"> <li>Albenis</li> </ul> </div> </div> </div> </div>

Solution解决方案

HTML: HTML:

<div class="parent-row">
  <h1>Add a new Post</h1>
  <div>
    <input type="text" class="put" />
    <button class="add">Add a Post</button>
    <button class="remove">Remove a Post</button>
  </div>
  <ul class="menu">
    <li>Albenis</li>
  </ul>
</div>

JavaScript: JavaScript:

const add = document.querySelector(".add");
const remove = document.querySelector(".remove");

add.addEventListener("click", function () {
  const cont = document.querySelector(".menu");
  const input = document.querySelector(".put");
  const newli = document.createElement("LI");

  newli.innerText = input.value;
  cont.append(newli);
});

remove.addEventListener("click", function () {
  const df = document.querySelector(".menu");
  df.firstElementChild.remove();
});

Working example: https://codesandbox.io/s/pensive-almeida-z82lr?file=/index.html:262-561工作示例: https : //codesandbox.io/s/pensive-almeida-z82lr?file=/index.html : 262-561


Your error你的错误

Your error was you were trying to get the newli constant from outside of its code block remember that const variables are scoped to there block.您的错误是您试图从其代码块外部获取newli常量请记住, const变量的作用域为该块。


A different way of doing this一种不同的方式来做到这一点

This way is a bit more simplified and allows you to delete anyone of the posts not just the last added.这种方式更简单,允许您删除任何帖子,而不仅仅是最后添加的帖子。

 const postBtn = document.querySelector('#post') const list = document.querySelector('#list') postBtn.addEventListener('click', () => { const text = document.querySelector('#post-text') list.innerHTML += `<li>${text.value} <button id="remove" onclick="remove(event)">remove</button></li>` text.value = '' }) const remove = (e) => { e.target.parentElement.remove() }
 <div> <h1>Make a post</h1> <input id="post-text" type="text" placeholder="Text"><button id="post">Post</button> <ul id="list"> </ul> </div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM