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>
<script type="text/javascript">
$(".delete").live("click", function (event) {
event.preventDefault();
var elementID = $(this).attr("id");
//other code
});
</script>
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?
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