Luke Luke - 1 year ago 53
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

to be found on the page. The class
) only appear after the Add More button has been added. (I've two different classes here because the field
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');
$(this).parents('#form').find($removeBtn).css('display', 'none');

I've created a fiddle here

Answer Source

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 :)

if($('class').length) {
    //Do something because it exists
} else {
   //Ok, now it doesn't exist
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download