-6

So,

How to check with JavaScript if DIV has that classname? Here's an example HTML <div class="cart"></div> that would be the parent and then JavaScript creates under that div's upon a click, but if it's already there and you click the item then it's just going to remove it. Example: Button is yellow and if you click it, it add's item to the cart and changes button class to selected. If you click it again, it will remove selected class and also remove item from the cart. I do have a code for the clicking part and adding it to cart, but not for removing it.. How could I do it?

JavaScript

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

Here it adds the item to the cart, but if you would reclick it, it will do it again. I've tried write a function, which checks that is the item already in cart, if it is then remove it, if not then add it, but I never succeed. I think that would solve my problem though.

Olaf Mudj
  • 3
  • 6
  • 2
    It is expected that you at least attempt to code this for yourself. Stack Overflow is not a code writing service. I would suggest that you do some additional research, either via Google or by searching SO, make an attempt and. if you still have trouble, come back with **your code** and explain what you have tried and why it did not work. – Paulie_D Apr 26 '16 at 09:05
  • I will edit my first post :) – Olaf Mudj Apr 26 '16 at 09:08
  • Possible duplicate of [Determine if an element has a CSS class with jQuery](http://stackoverflow.com/questions/263232/determine-if-an-element-has-a-css-class-with-jquery) – JJJ Apr 26 '16 at 09:15

1 Answers1

1

try the following:

   $(".item-card").click(function() {
  var itemnume = $(this).find("img").attr("title");
  var replaced = itemnume.split(' ').join('_');

  if ($(this).hasClass('selected-item')) {
    console.log()
    $("#" + replaced).remove();
  } else {
    $("#itemcart").append($("<div id=" + replaced + ">" + itemnume + "</div>"));
  }
  $(this).toggleClass("selected-item");
});

https://jsfiddle.net/0tusd19b/

madalinivascu
  • 32,064
  • 4
  • 39
  • 55