views:

108

answers:

3

What is the best-practise way of Identifying dynamically generated element on page?

Let me explain. I have a list of elements, there can be as few or as many elements as the user defines, on a page. Each one of these corresponds to an item each with it's own id. Now, the user has the ability to edit or delete these elements on the page and these operations are handled with jQuery. Each element comes with a link per operation they can action (i.e delete and edit).

Now a problem is knowing which element the user has selected. To deal with this I give each link the ID of the element as an ID attribute, which I then obtain using jQuery:

 <a href="#" class="delete" id="<%= Model.elementID%>">Delete</a>

  $(".delete").live("click", function(event) {
      event.preventDefault();
      var elementID =  $(this).attr("id");
      //other code
   });

This is obviously far from ideal as it would mean many DOM elements could have the same ID. Alternatively I could create my own attribute such as elementID but I believe this breaks standards.

So what could you recommend. How can I identify dynamically generated elements on a page?

A: 

Why not just add a class instead. This also solves the issue of having multiple id's which as you eluded to is not allowed and will cause major issues with subsequent jquery operations.

<a href="#" class="delete" id="<%= Model.elementID%>">Delete</a>

  $(".delete").live("click", function(event) {
      event.preventDefault();
      //other code
      $(yourNewElement).addClass('noob');

   });
redsquare
How could I identify the class from JavaScript? Considering they could have many classes?
Damien
you could always append the existing id to the new element with a prefix so noob_OriginalElementId
redsquare
this then allows you to split the string to get back the original id
redsquare
Yeah Prefixing the ID was something that occurred to me, I think that's what similar sites do.
Damien
A: 

One other thing you could do is this:

<a href="#<%= Model.elementID%>" class="delete"> Delete </a>
$(".delete").live("click", function(event) {
    event.preventDefault();
    var elementID =  $(this).attr("href");
    // strip the preceding '#'

    // rest of your code
});

PS: everything does not have a best practise. Some things just need a new appoach.

Cheers, jrh

Here Be Wolves
+2  A: 

I've done this quite a bit for my sites and my solution is a combination of where you started from and some of the comments:

Use a naming convention, like "element_type:id:action". So your example's generated be "element:23:delete". Then you can split() the .attr("id") that you've grabbed and determine what it is ("report" vs "folder"), the id, and what you want to do ("delete", "edit", "move").

This has worked out very well for me, and is very scalable.

I'd keep the class, though, so that you can easily attach events via jquery.

James

James S