Checking if a div element contains a child with a specific class name using JavaScript

Okay, so here's the dilemma:

Is there a way to use JavaScript to determine if a DIV has a specific classname? For instance, consider this sample HTML

<div class="cart"></div>
. This DIV would act as the parent, and JavaScript would dynamically create child divs underneath it upon clicking. However, if a child div is already present and you click on the item, it should be removed. For example, imagine a button that turns yellow when clicked, adding an item to the cart and changing the button's class to "selected." Clicking the button again should remove the selected class and eliminate the item from the cart. I have code for adding items to the cart, but I'm struggling with removing them. Any suggestions?

JavaScript

    $(".item-card").mousedown(function() {
        $(this).toggleClass("selected-item");
        var itemName = $(this).find("img").attr("title");
        $("#itemcart").append($("<div id="+itemName+">"+itemName+"</div>"));
    });

Currently, clicking repeatedly adds the item to the cart multiple times. I've attempted to create a function that checks if the item is already in the cart, removes it if present, and adds it if not. However, I haven't been successful in implementing this. I believe addressing this issue would resolve my problem.

Answer №1

Here is a helpful suggestion:

   $(".clickable-item").click(function() {
  var itemName = $(this).find("img").attr("title");
  var modifiedName = itemName.split(' ').join('_');

  if ($(this).hasClass('selected')) {
    console.log()
    $("#" + modifiedName).remove();
  } else {
    $("#cart").append($("<div id=" + modifiedName + ">" + itemName + "</div>"));
  }
  $(this).toggleClass("selected");
});

https://jsfiddle.net/1a2b3c4d/

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

Navigating through the features of www.addthis.com is simple and straightforward

I am looking to integrate the addthis.com plugin into my website. Specifically, I want to pass my own data to the plugin when users click on the email link. This data should then be sent to the client. Is there a way to achieve this? ...

Ensuring scope safety in jQuery AJAX requests

My intuition suggests that if I am on a laggy server and the user triggers two events quickly enough, the value of c in the success function will be based on the most recent event, potentially causing func1 to use the incorrect value. This is merely a hypo ...

Using location.reload with the argument of true is no longer recommended

While it's generally not recommended to reload an Angular Single Page Application, there are situations where a full reload is necessary. I've been informed by TSLint that reloading is deprecated. Is there any other solution available for this ...

Tips for changing the color of shapes when hovering over an image state

I have arranged three images in a column and applied column-count: 3; along with setting border-width for those images. Now I am curious about how to create the hover state for these images. Here is the HTML code snippet: <div class="wrap"> < ...

Encountering difficulties with updating customer information in postgreSQL

I am attempting to perform CRUD operations using pg-promises and stored procedures in PostgreSQL. Here is my code: controller.js: const db = require("./../index.js"); exports.getAllData = async (req, res, next) => { try { const data = ...

Internet Explorer 9 crashing when using a jQuery file change event

Here is the HTML code snippet I'm working with: <div class="s-field" id="fileBox"> <div style="display: block; width: 100px; height: 20px; overflow: hidden;"> <button style="width: 110px; height: 30px; position: relative; top ...

Access to the Express Node.js server is restricted to the machine that is currently hosting the server

I am facing a beginner issue with using express. I am on Ubuntu 14.04 and created a new directory where I ran "express" in the terminal to set up a project template. Following that, I ran "npm install" to install the dependencies. I then made changes to &a ...

Displaying a verification button prior to sending out the form

My website has a straightforward form that sends data to the backend when a button is clicked. To handle this process, I created a function. Before the data is sent, I wanted to display a confirmation panel. Below is the code snippet for the function that ...

Deliver search findings that are determined by matching criteria, rather than by identification numbers

I am seeking to return a JSON match upon form submission, rather than simply searching for a specific ID. However, I am uncertain about how to structure this. I have the ability to search for the necessary match in a JavaScript document within one of my n ...

Error: The function jQuery(...).hexColorPicker does not exist

I am attempting to utilize a color-picker jQuery plugin. Below is a screenshot of the JavaScript file: https://i.stack.imgur.com/ovRjx.png Here is the code I am using to initialize it: <script type="text/javascript> jQuery(function(){ ...

Collapse all "Read More" buttons simultaneously using Bootstrap

I am attempting to design a segment that contains multiple paragraphs that can be expanded or collapsed individually. How can I achieve this using only pure bootstrap css so that they do not all expand and collapse simultaneously? #summary { font-size: ...

Ensure that the ng-view element has a height of 100% and

Currently, I am working on developing an AngularJS app and my index page consists of a ng-view where all the content is injected using ui-router: <header> <nav class="navbar"> //content for navbar will go here </nav </hea ...

Can you explain the differentiating factors of a document and the DOM?

I recently read an article discussing the distinction between jQuery's bind() and live() functions. You can check it out here: http://msdn.microsoft.com/en-gb/scriptjunkie/ee730275.aspx (specifically the Live and Let Die section). The bind function ...

I encountered a CORS policy error while using React. What steps can I take to effectively manage and resolve this

INDEX.JS import express from "express"; import { APP_PORT } from "./config"; import db from "./database"; import cors from "cors"; import bodyParser from "body-parser"; import Routes from "./routes&quo ...

Tips for connecting to multiple items in an md-select element from within a directive

Looking to develop a straightforward directive that displays either a textbox or dropdown based on whether an array is provided for the model property on the scope. Any value other than explicitly setting false in the directive markup such as multiple="fa ...

Displaying jQuery AJAX response through the use of a PHP script as a middle

After setting up an AJAX request that functions correctly, I encountered a problem with retrieving and displaying the data received from the request. Here's the script in question: var input = $("#input").val(); $(".pure-button").click(function() { ...

What is the best way to extract row data from a datatable and transmit it in JSON format?

I have successfully created a code that retrieves data from a dynamic table using ajax. However, I am facing an issue where I only want to send data from checked rows. Despite trying different approaches, I keep encountering errors or receive an empty arra ...

The required element was not discovered

Whenever I attempt to execute npm run serve, it reaches 98% completion and then halts, displaying the following error message: An issue occurred while compiling with a total of 1 error: ...

Is there a way to use Media Queries to require CSS to load an image?

Here is the CSS code I am using: html { background: url(../img/header_mobile.jpg) no-repeat center center fixed; -webkit-background-size: cover; -moz-background-size: cover; -o-background-size: cover; background-size: cover; } /* Smal ...

Unable to trigger JQuery .blur event

I am currently working on implementing server-side validation for an input field that needs to be validated when it loses focus. However, I'm running into an issue where the alert is not triggered when the input field loses focus. Here's a snipp ...