bgadoci
bgadoci

Reputation: 6493

Creating unique IDs with JQuery

This question is prob a duplicate (but I can't find it) so I apologize if it's redundant. I am trying to use JQuery's .remove function to allow for removing (obviously) of li elements in my static HTML prototype. Rather than write out a javascript block for each li I want to remove I was wondering if it was possible to create incrementing IDs with JS alone. (I'm using Serve with HAML and SASS fyi). Here is what I have.

/view-file.html.haml

%ul
  %li#removeThis1
    %a.remover1{:src => "#"} Remove

/application.js

...
$(".remover1").click(function () {
  $("li#removeThis1").fadeOut( function() { $(this).remove(); });
});

Any thoughts on how to increment .remover1 to .remover2, etc? Likewise li##removeThis1 to #removeThis2, etc.

I would need all this to happen on page load.

Upvotes: 0

Views: 553

Answers (1)

user1106925
user1106925

Reputation:

There's an ancestral relationship between the elements, so just use that to your advantage.

  // don't bother numbering the class. Use a common class
$(".remover").click(function () {

       // find the closest ancestor with an ID that start with "removeThis"
    $(this).closest("li[id^=removeThis]")
           .fadeOut( function() { $(this).remove(); });
});

Or if you don't really need an ID on the ancestor, use a class there too...

  // don't bother numbering the class. Use a common class
$(".remover").click(function () {

       // find the closest ancestor with the class "removeThis"
    $(this).closest(".removeThis")
           .fadeOut( function() { $(this).remove(); });
});

Ultimately, if you were to use IDs, you'd want to generate them on the server side, then extract the numeric portion of the ID from the element with the handler, and concatenate it into the selector for the ancestor.

Upvotes: 2

Related Questions