Skip to content Skip to sidebar Skip to footer

Multiple Identical IDs In The Same HTML Document

I am creating a web page that includes several HTML-templates that may contain IDs. As a result the final page may contain several HTML element with the exact same ID which is not

Solution 1:

The $(selector, context) syntax will always only search within the given context, so as long as your ID's are unique within that context, your jQuery should work in all browsers.

As you realize, though, it is ill-advised to use ID's in this manner, in templates.

Since multiple identical ID's are not allowed, there is no specification for how they should be handled. It can never be guaranteed that all browsers will continue to support the code you're writing. That code will behave the way you expect on all major browsers today, though.

Workarounds would be using classes, or logic in your templating engine to ensure unique ID's, e.g. templateID-control-2-myButton.


Solution 2:

As long as you use jQuery context, e.g. $('#some-id', context), it will work fine.

But you should really use class names instead of IDs for elements that occur more than once in a page.


Solution 3:

No browser will deny you multiple ID's but it is bad practice. An "ID" tag is a Unique Identifier for an object within the Document Object Model (DOM). If you aim to be using jQuery with these ID's you need to come up with another solution. Note: Your code will still function perfectly fine, and will render in every browser. Just puts a lot more stress on the DOM if your querying it all the time and they all have the same ID! (Plus, not very maintainable)

If you need each template to have the same ID, consider using a class (i.e. .template) or even a custom attribute (i.e <div class="something" mycustomid="1"> then use $(.something).attr('mycustomid') to access it. (Note: W3C HTML Validator doesn't validate this)

if you really insist on using ID, but want to make the code better, try prefixing something unique to the start of the id (Even the index of an iterator if your templates are created that way), then use jQuery to do a regex match.

It's not much of an answer, but I don't have enough information :)


Post a Comment for "Multiple Identical IDs In The Same HTML Document"