Is it normal to have two elements with same id in

2020-02-10 14:25发布

i know, that two elements can't hav the same id. But it's happens so, that in my project i have two elements with same id in other divs, like this

<div id="div1">
     <img id="loading" />
</div>
<div id="div2">
     <img id="loading" />
</div>

and css:

#div1 #loading
{
    some style here...
}
#div2 #loading
{
    another style here...
}

works fine for me, but maybe it is not reccomended to do by so?

Thanks

UPDATE

Yes, i know, thet i can use classes, and it's strongly recomended to do by so, but i want to know is there any potential risk in this usage of id? i think no, becouse when i wrote for example

$("#div1 #loading")... it becomes a unique element. isn't it?

Final Update

Use suggested principe, if you have reasons to do that! ;)

13条回答
做个烂人
2楼-- · 2020-02-10 14:58

It's bad practice of using I'd on element. Because I'd giving something for understanding unique with their name identification. And second thing we use its in CSS but in JavaScript this bad practice. So good example for this class and student.

So don't do this.

查看更多
贪生不怕死
3楼-- · 2020-02-10 15:00

Yes you are right, it is not recommened to do so. An ID should always be unique (e.g. if you want to select the element with javascript). If you just want to add the same style to the divs, just use css class.

查看更多
男人必须洒脱
4楼-- · 2020-02-10 15:01

IDs should be unique, so id1 and id2 are fine, but for many elements with the same style, use an HTML class and CSS class selector:

.loading
{
styles here
}

These are allowed to be repeated as many times as you want on a page :)

查看更多
▲ chillily
5楼-- · 2020-02-10 15:02

Is it normal? No.

Is it recommended? Definitely not! It's actually prohibited (but enforcement is weak).

But it (apparently) works, so ...

查看更多
Emotional °昔
6楼-- · 2020-02-10 15:02

https://www.w3.org/TR/1999/REC-html401-19991224/struct/global.html#adef-id

enter image description here

BUT!

If you need it in your project, you can use it, like suggested in my Question Final Update!

查看更多
霸刀☆藐视天下
7楼-- · 2020-02-10 15:02

I disagree on people saying to always use a "unique", meaning different ID everytime you label one. Sometimes its acceptable, such as my case where I am making a calculator.

The javascript is doing the math and outputting the result into the div with the id="total". I need that same exact "total" to be in 2 different places however. In this case, why wouldn't I use two different div's with the same ID? I need the same number in both boxes. With jQuery, I perform and output the math once and it populates both div's at the same time, which is what I want.

So long as you understand the risks where if you were PULLING information from those 2 div's with the same ID, then I say feel free. As long as you dont confuse yourself and need 2 different results in the same div ID.

查看更多
登录 后发表回答