skip to Main Content

I am designing a booking site and I want by clicking the delete button the whole text and the delete button get deleted, because my button has two classes, className wouldn’t retrieve the specific class name and the event doesn’t get applied on the element, so is there any solution for this className behaviour?

let deleteObject = document.querySelector("main");
deleteObject.addEventListener("click", event => {
  if (event.target.className === "deleteButton") {
    event.target.parentElement.parentElement.removeChild(event.target.parentElement)
  }
})
main {
  display: grid;
  grid-template: repeat(5, 35px)/repeat(2, 200px);
  justify-items: center;
  align-items: center;
}

.search {
  grid-row: 1;
  grid-column: 1/span2;
}

.book1 {
  grid-row: 2;
  grid-column: 1;
}

.book2 {
  grid-row: 3;
  grid-column: 1;
}

.hide {
  grid-row: 4;
  grid-column: 1/span2;
  margin-left: 0;
}

.bookButton1 {
  grid-row: 2;
  grid-column: 2;
}

.bookButton2 {
  grid-row: 3;
  grid-column: 2;
}

.add {
  grid-row: 5;
  grid-column: 1/span2;
}
<main>
  <form action="" class="search">
    <input type="text">
  </form>

  <p class="book1">Harry Potter</p>
  <button class="bookButton1 deleteButton">Delete</button>

  <p class="book2">Lord of The Ring</p>
  <button class="bookButton2 deleteButton">Delete</button>


  <div class="hide">
    <input type="checkbox" id="hide">
    <label for="hide">Hide All</label>
  </div>

  <form class="add">
    <input class="addBook" type="text" placeholder="e.g Harry Potter" name="" id="">
    <button class="add">Add</button>
  </form>
</main>

2

Answers


  1. You can check if the element matches a CSS selector with Element#matches:

    if (event.target.matches('.dr'))
    
    Login or Signup to reply.
  2. Since your event checks for a class named "dr" it is expected behavior that no element is deleted since there isn’t a single element associated with that class.

    Classes are meant to be generic and used by different elements of the DOM.
    You should consider using IDs as well as other HTML elements to encapsulate the elements to select in your javascript code in order to only target the elements to delete.
    Consider as well to use classList instead of className on elements with more than one class. An element can be associated to multiple classes by simply listing the classes separated by spaces in the class attribute of the tag.

    <span class="firstClass secondClass">Foo</span>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search