Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
947 views
in Technique[技术] by (71.8m points)

javascript - Is it normal to have two elements with same id in two div elements with other id?

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?

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, because when I wrote for example

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Change your id to class. It is not a good idea to give duplicate id.

Think two students having same roll no in a class. Imagine them getting examination result. How will the school be able to recognise the marksheet?

Your way is not cross browser compatible, and will affect a lot while coding JavaScript, and posted form etc

You can get the same effect using class

see

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

and css:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share

2.1m questions

2.1m answers

63 comments

56.6k users

...