Multiple Identical IDs in One HTML Document

I am creating a web page with several HTML templates that can contain IDs. As a result, the resulting page may contain multiple HTML elements with the same ID, which is not allowed by HTML

However, I can solve this problem using jQuery contexts like: $ ("# id54", template4), but will this work in all browsers or will some browsers refuse me multiple IDs?

+3


source to share


3 answers


The syntax $(selector, context)

will always only look in the given context, so if your id is unique in that context, your jQuery should work in all browsers.

However, as you can imagine, it is not recommended to use the identifier in this way in templates.



Since multiple identical identifiers are not allowed, there is no specification for how they should be handled. Can never guarantee that all browsers will continue to support the code you write. However, this code will behave as you expect in all major browsers.

Workarounds would use classes or logic in your template to provide unique identifiers eg. templateID-control-2-MyButton.

+10


source


As long as you are using jQuery context eg. $('#some-id', context)

, it will work fine.



But you should really use class names instead of IDs for elements that appear more than once on the page.

+4


source


No browser will deny you multiple IDs, but this is bad practice. The ID tag is a unique identifier for an object in the Document Object Model (DOM). If you want to use jQuery with this ID, you need to come up with a different solution. Note. Your code will still function perfectly and will display in every browser. Just puts a lot more emphasis on the DOM if you keep asking for it and they all have the same ID! (Also not very convenient to service)

If you need every 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 (Note : W3C HTML Validator does not validate this)

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

This is not much of an answer, but I am missing information :)

+1


source







All Articles