Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 797
Simon Avatar asked Jun 22 '10 12:06

Simon


People also ask

Can 2 divs have same ID?

The HTML id attribute is used to specify a unique id for an HTML element. You cannot have more than one element with the same id in an HTML document.

Can multiple elements have the same ID CSS?

This is because an id value can be given to only one HTML element, in other words, multiple elements cannot have the same id value on the same page. For example, you can have only one element with a #header id or one element with a #footer id on your page.


1 Answers

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...
}
like image 115
Starx Avatar answered Oct 01 '22 22:10

Starx