Multiple identical IDs in the same HTML document

后端 未结 3 1978
挽巷
挽巷 2020-12-21 06:10

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

3条回答
  •  不知归路
    2020-12-21 06:46

    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

    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 :)

提交回复
热议问题