简体   繁体   中英

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 . 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:

<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:

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


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.


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>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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