Michael Schwartz
Michael Schwartz

Reputation: 8415

Check if Element/ID/Class is Added Before Append

http://jsbin.com/palavuso/1/edit

You start with a blank canvas. Click the add button and BAM.... we have a button

$(".add-query").on('click', function() {
  $(".beauty-btns").append("<a class='" + $('.mediaquery-slider').val() + "' href='javascript:void(0)'>" + $('.mediaquery-slider').val() + "px</a>");

  // Remove Query
  $(".beauty-btns").find("a").on('click', function() {
    $(this).remove();
  });
});

Simple I know; However what if the class or ID already exists?
Well if it's a class we can add multiple, but not in my experiment.

What I'm trying to do is add the button, but if the class already exists alert the user and ask them if they want to replace the button or cancel.

I know I can use window.confirm for the alert process here, but after that I'm confused.

Example:

    var x = window.confirm("Are you sure you want to refresh the page?")
    if (x)
      location.reload(true);
    else
      return false;

Any help is greatly appreciated.

Upvotes: 0

Views: 101

Answers (1)

MarioDS
MarioDS

Reputation: 13063

To check if a class exists, simply select it and see if there is anything with length:

var val = $('.mediaquery-slider').val();
var $button = $(".beauty-btns").find('a.' + val);
//notice the . after a for "select by class".

//$button is supposed to contain an array of matches, length = 0 with no match
if($button.length > 0) {
    alert("Button already exists!");
}

Now for the code about replacing it, you almost have it:

var x = window.confirm("Button exists, replace it?") //will give OK/Cancel buttons
if (x)
  $button.replaceWith("<a class='" + $('.mediaquery-slider').val() + "' href='javascript:void(0)'>" + $('.mediaquery-slider').val() + "px</a>");
else
  return false; //Depending on the situation you could just leave off the else block.

Notes

  • Your classes will start with a number if I'm not mistaken. This is not valid. Prepend a letter instead:

    var val = 'button-' + $('.mediaquery-slider').val();
    
  • It's actually better to use ID's in your case as supposedly there can only be one button for each slider value.

  • I don't really see why you would want to replace the buttons. After all,you replace them with the exact same HTML. You would lose all the event handlers and other javascript data on them. And now that I notice, you're attaching handlers in a wrong way!

Store the class that you used for appending the last button, and then only set a click handler on that one:

$(".beauty-btns").find("a." + val).on('click', function() {
    $(this).remove();
});

If you don't do this, every existing button will keep getting new click handlers everytime you add one. That's not efficient in terms of memory and performance.

Upvotes: 1

Related Questions