Why use id when you have class? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why use id when you have class?

Doesn't class make id kind of irrelevant?

18th Nov 2016, 3:18 AM
Hakeem Thomas
Hakeem Thomas - avatar
3 Answers
+ 2
class can be assigned to multiple elements, however id can be only assigned to one element. when you access a class through css or js, it searches for all elements with the class name. but when you access an id through css or js, it just searches for the first element with that id and ignores the rest. so, in a way using id is faster.
18th Nov 2016, 3:39 AM
Nikunj Arora
Nikunj Arora - avatar
0
JavaScript would select first id and ignore all the other ids unless you tell it to look for more. CSS would throw a silent exception, that would be resolved by the browser and all elements would be selected
18th Nov 2016, 4:05 PM
Dawid Borusiak
Dawid Borusiak - avatar
0
strictly speaking, you use both for different reasons. You would assign one element one Id , as in your school or personal Id, no two persons can have the same id. that helps when you want to differentiate one element from the rest of your page, and you want the ability to pinpoint that element. say one cell in a table. whereas class, it is like your class at school, you use to identify a group of elements that you want to treat similarly. say a group of cells in a table. extra thoughts, despite what I said, practically you can use a class in love of an I'd, like having a class with one student. it will work but it's inefficient. while, the other way around shouldn't work, one I'd should refer to one element, as in one student. despite that most browsers, will try and mitigate that issue. you should try to get your code working correctly, in first place. without waiting for the browser to do that for you, since you can't really always depend on that.
24th Nov 2016, 2:54 PM
Mohamed Elliethy
Mohamed Elliethy - avatar