Can two html elements have the same id but in different classes?

南楼画角 提交于 2020-03-22 05:37:41

问题


I was writing a javascript for an existing application in which there are two forms with separate ids, and in each form there is a div which has the id "validationSummary". But these divs belong to different classes. So my question is can this be possible? Please anyone can explain me is this correct ?

These are the divs:

<form id="foo" .....>
<div class="notice_bar validation-summary-errors error_message" id="validationSummary"></div>
</form>

<form id="bar" .....>
<div class="validation-summary-valid notice_bar affirmative_message" id="validationSummary"></div>
</form>

and also the class notice_bar is common leading to other confusion!


回答1:


Possible? Yes. Good coding? No.

From w3.org:

ID and NAME tokens must begin with a letter ([A-Za-z]) and may be followed by any number of letters, digits ([0-9]), hyphens ("-"), underscores ("_"), colons (":"), and periods (".").




回答2:


A unique identifier for the element.

There must not be multiple elements in a document that have the same id value.

Taken from w3.org.

The id attribute specifies a unique id for an HTML element (the value must be unique within the HTML document).

Taken from W3Schools.




回答3:


It should work just fine, but it isn't a good practice. Redundancy isn't necessarily a good thing.




回答4:


It should work...i worked on an app that created the same id, and i use to have same IDs on the page at the same time. It's not good practice because IDs are meant to be unique, but unless you need to use some JavaScript to run something from that specific id (in your case validationSummary ) it should work. As already said, it's not what IDs are meant for tho.



来源:https://stackoverflow.com/questions/33709026/can-two-html-elements-have-the-same-id-but-in-different-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!