Luke Luke - 5 months ago 12
Javascript Question

Add/ remove element based on presence/ absence of class

I'm looking for the remove button to disappear but only if only there is no

.newCar
to be found on the page. The class
newCar
(and
newDate
) only appear after the Add More button has been added. (I've two different classes here because the field
.newDate
can't be cloned because I need a new calendar generated each time.)

In short, the Remove button should only appear if there is more than one car (i.e. the fields in the fieldset are cloned).

I've been trying various techniques and my current one is to use the .hasClass method but I'm unsure as to why it's not working.

if ($('.core:last').hasClass('newCar')){
$(this).parents('#form').find($removeBtn).css('display', 'block');
}
else{
$(this).parents('#form').find($removeBtn).css('display', 'none');
}


I've created a fiddle here

Answer

Ok, first of all I updated your Fiddle, check the link at the bottom of the post. This is what I suggest.

  1. You where only checking the 'newCar' when pressing the "Add more cars" button, you should also check it when you remove things. Because of that I made the check a function.

  2. You wrote the check very complex. $('class').length is sufficient in this case (you can see it in the fiddle how I fixed it). You can check if an element exists by doing it this way:

  3. You don't have to change the CSS for an element to hide it or show it, you can just use $('class').hide(); or $('class').show();. That does the same as setting the display to block or none.

Further I would suggest you check your code some more, there is a lot that can be shorter and better. But then again, we all start somewhere :)

https://jsfiddle.net/218csoy7/5/

if($('class').length) {
    //Do something because it exists
} else {
   //Ok, now it doesn't exist
}