Is using the same id multiple times on a page bad

2019-02-21 17:22发布

I understand that using the same id multiple times in a page creates malformed html. When using a jquery selector only the first element with the id will be returned, but in my application I shouldn't be running into this issue.

I have list of items views that will all have an element I need to refer to. Since each item only has access to its own $el passing in an id selector for something will not produce any conflicts (even if there are multiple on the page).

I've simulated what I mean in a fiddle here

In this project I am not doing any page wide parses so I believe it should be safe. Is there any reason why I should not be doing this?

4条回答
祖国的老花朵
2楼-- · 2019-02-21 17:42

http://www.w3.org/TR/WCAG20-TECHS/H93.html

http://www.w3.org/TR/html401/struct/global.html#adef-id

There are other things that read your HTML document, not just browsers.

According to the HTML specification, the id attribute MUST be unique on a page (it's not a criteria web designers/developers just invented)

查看更多
我只想做你的唯一
3楼-- · 2019-02-21 17:50

yes it is bad practice. An id should be a unique reference to that element. Use class instead.

查看更多
淡お忘
4楼-- · 2019-02-21 17:55

You only know what the current requirements are.

It is best to keep to standards and to valid code/markup as you don't know what will happen in the future.

In this application, you may very well end up having to use jQuery and then you will be in trouble.

The solution for styling multiple elements the same way is to use CSS classes - there is absolutely no reason not to do so, as it is just as simple as using ids.

查看更多
时光不老,我们不散
5楼-- · 2019-02-21 18:01

Absolutely. The specs for HTML, CSS, and JavaScript are an agreement as to how a browser will behave when confronted with certain code. Browsers don't make many guarantees when you do anything that's off-spec, and they make even fewer that they would all agree on.

As Oded mentioned in his comment on the question, browsers build a DOM tree from your code, style it, and render it. So, depending on how a given browser decided to do that, they may run into problems with multiple elements with the same id.

So, why risk it? I can't think of any instance where a class (or nothing at all) couldn't be used in place of an id.

查看更多
登录 后发表回答