Is there a way to trigger an event on a particular class within the DOM when my element has several different classes attached to it?

When developing a booking platform, I encountered an issue with deleting text and buttons. Since my delete button has two classes, using className could not properly identify the specific class needed for deletion. Additionally, the event was not being applied to the element. Is there a solution to correct this behavior of the className?

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>

Answer №1

To determine if the element corresponds to a CSS selector, you can utilize Element#matches:

if (event.target.matches('.dr'))

Answer №2

When your event is searching for a class called "dr," it's normal that no element gets deleted if there isn't a specific element linked to that class.

Classes are designed to be general and utilized by various DOM elements.
It might be helpful to incorporate IDs along with other HTML elements to group the elements you want to target in your javascript code for deletion. Additionally, consider using classList rather than className on elements with multiple classes. You can assign multiple classes to an element by listing them separated by spaces in the class attribute of the tag.

<span class="firstClass secondClass">Foo</span>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Troubleshooting the Issue with WordPress Image Customization Settings

I'm in the process of designing a Wordpress theme, but I've hit a roadblock. I'm utilizing the theme customize page to upload both a main logo and a mobile logo, which should then be displayed on the page. Initially, it was working for about ...

Guide on how to create multiple bundles using browserify and gulp

I have successfully implemented browserify to bundle up my files, but now I am faced with the challenge of generating multiple bundles. Specifically, I want to create dist/appBundle.js and dist/publicBundle.js. gulp.task("js", function(){ return brow ...

The error message states: "Dygraph is not defined."

Currently, I am utilizing express.js in my application to render dygraph charts on the client side. You can take a look at my index.jade file here. Upon visiting my browser, an error pops up in the console: Uncaught ReferenceError: Dygraph is not defined. ...

Utilize React JS to serialize form data for submission via a POST request

I have a simple form where users input text and it triggers an AJAX request to create a new comment. var CommentForm = React.createClass({ propTypes: { // ... // ... }, handleFormSubmit: function(e) { e.preventDefault(); var compo ...

Leveraging Google Sheets as a Dynamic Database with Ajax

I found a helpful guide on using Google Sheets as a database with Apps Script and ajax. Here is the link. I understand that I need to include 'Google Sheet/Apps Script Code' in a spreadsheet. However, I'm unsure about what needs to be place ...

Is it necessary to include refs as dependencies in the useEffect hook and other similar functions?

From my understanding, the containers retrieved using useRef are consistently the same. However, when referencing them in functions like useEffect, it triggers an eslint exhaustive-deps warning. Is it acceptable to disregard the warning in this scenario, ...

Is it window.jQuery or just jQuery?

(function($) { // plugin code })(window.jQuery); It appears that this code produces almost the same effect as: (function($) { // plugin code })(jQuery); Is it necessary to use window.jQuery instead of just jQuery as the function argument? Does it serve ...

Extract the complete HTML information from the weather website

Currently, I am attempting to retrieve weather data from the following website: using this code snippet: try { int i = 0; if (googlefirst3.startsWith("http")) { Document document = Jsoup.connect("https ...

struggling to implement promises in mongoose operations

Can anyone explain why this promise setup is not functioning as expected? The goal was to remove the documents, add new ones, find them, and then output the data, but it's not displaying anything. var Comp = require("./models/company.js"); var ar ...

When attempting to use the $http get command, an error may occur due

Is there a way to capture these errors in an Ionic application? ionic.bundle.js:25000 GET net::ERR_CONNECTION_REFUSED Using the following code snippet: $http.get('http://' + ip + '/?custom=1&cmd=' + cmd); I have attempted var ...

Creating HighStock charts on the server-side using NodeJS

I'm currently utilizing HighStock to create charts within the browser. However, I now have a need to save some of these charts on the server. While I understand that HighCharts offers an export option to the server, I am interested in exploring other ...

Synchronous: Establishing a connection to MongoDB once the server has successfully launched

I am curious to understand the interaction between Node.js asynchronous functions and MongoDB. If the server initializes before establishing a connection, and if my templates or Ajax requests rely on database data, will the serving of the HTML fail or will ...

Greeting message in jQuery that only disappears when manually closed (for Rails 3)

How can I create a welcome message for first-time users in Rails 3 that remains visible until the user closes it once using jQuery's hide method? ...

Generating JSON data on the fly using D3.js scripting

I am attempting to create a JSON object dynamically by pulling data from an array in D3 JavaScript. (The code below is not the exact one I used, but similar) let radius = [10,20,30]; let jsonradius = '[{'; for (let i = 0; i < radius.le ...

Having issues getting the single div to refresh with `.#div.load(scriptpage.php)` command

I've been attempting to update the content of a specific div (in-game chat) every X seconds or minutes using this simple code. The issue I'm facing is that the content never refreshes or loads the new page. I've searched through various cod ...

Pass an array from a script file in JavaScript to index.js within the Express framework

I've encountered a challenge in sending an array (or JSON object) from script.js to index.js, my express server file. I've explored various solutions such as passing the variable through an HTML file and then to another JavaScript file, utilizing ...

Learning how to activate automatic sliding in a bootstrap carousel featuring 2 images and a video every 10 seconds

I am attempting to create a unique slider that combines both images and videos. Despite trying to implement it using bootstrap, I have been unsuccessful so far. See the code snippet below: <div id="carousel-slider" class="carousel slide carousel-fade ...

Utilize Bootstrap to occupy the rest of the available vertical space

Struggling with handling empty space in a Bootstrap grid? Check out the issue I'm facing when the div doesn't fill the entire height. https://i.sstatic.net/zvS7t.png This is the current configuration: <div class="row"> <div class= ...

What is the best way to ensure a sidebar's height matches the height of the content in a two-column table using div elements?

Just finished setting up a 2-column layout with a content div, sidebar div, header, and footer. You can check out the live example here. Any tips on how to make the sidebar's height match the content height (like a 2-column table)? Utilizing jquery ...

Discover the steps to linking a dropdown menu to a text input using HTML and JavaScript

I'm currently using Sublime and trying to link a dropdown menu with an input text using html, css, and javascript. When the user selects an option from the dropdown menu, I want the corresponding value to appear in the text input field. For example, i ...