Reputation: 1349
Specifically, I have areas of my (heavily JS) web page that contain lists of HTML elements and for simplicity let's assume there are just two lists: A and B. Let's also say When I click on the first item in list A (A1) something happens to the first item in list B (B1).
I gave each element in list A a common HTML class and an ID (like <li class='listAmember' id='1'>...</li>
). I set up elements in list B in a similar way (like <li class='listBmember' id='1'>
). Then I attached some click
handlers (using jQuery in this case) and ran into problems with duplicate IDs, even if I qualified my jQuery id-based selectors with the class name, like this
$('.listAmember#1').click(function(){});
I've realised that this is bad practice (IDs are supposed to be unique in the document!) but I'm unsure what good alternatives there are.
I don't really want to create IDs like listAmember-1
because if I have, say, a lookup-table in my JS code that is keyed on the numeric ID, I'd need to parse out the 1
from that ID string to get the 'real' ID. (And I would still need to add a class like listAmember
for styling purposes and that seems unnecessarily repetitious?) All in all that seems clumsy and I assume there are better ways?
Upvotes: 1
Views: 162
Reputation: 289
For Unified ID's maybe in a System that has external Libarys in use, you should always attach them with a Namespace. For Example like: "myFancySlider-container" This helps to keep names Unique for your special application.
If you generate Dynamic Code, you have to Make sure, to only create One of each object. Or you Assemble them With iterations. An alternative to that, could be the unifying with Timestamps.
EDIT As others already mentioned, you should avoid Using ID's as you can. ID's only make sense, to benefit from the Unique Attributes. For example, you know exactly what element you want, so an ID can be a verry good shortcut for that. Specialy in dynamic Content Applications.
Upvotes: 0
Reputation: 1496
As Florent says, I would try and avoid IDs altogether. One convention is to use class names like js-list-a
to signify it's a class intended for JavaScript usage only. Then you're free to start using the index of the li
within the list.
Also, you could just set one click
handler on the list and use event delegation .
A combination of these ideas means you won't have to touch IDs.
Upvotes: 1