Why does the id selector have to be used once per page while class selector can be used multiple times. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Why does the id selector have to be used once per page while class selector can be used multiple times.

What will happen if I used #first in three different sections in one page? Since the rule specify that it must be used once per page.

4th Sep 2017, 10:31 AM
Delani
Delani - avatar
4 Answers
+ 4
id is unique, repetition will cause an error
4th Sep 2017, 10:38 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 3
For grouping use classes
4th Sep 2017, 10:38 AM
👑 Prometheus 🇸🇬
👑 Prometheus 🇸🇬 - avatar
+ 3
You can jump to any element with its id using link. like <p id="fa">Jump</p> You can jump to this p element using link ending with #fa e.g. www.abc.com/#fa If you will have same id in different elements, the browser will get confused where to jump that's why it is recommended to use unique of for different elements
4th Sep 2017, 10:38 AM
Kartikey Sahu
Kartikey Sahu - avatar
+ 2
Id guarantee (as long as coder follow rules) that it's unique. If you want an identifier to be applied on many element the 'class' attribute is designed for that specificly different purpose of 'id'... The two main differences between 'id' and 'class' attribute are: + 'id' is unique in whole document for a specific element, while 'class' can be applied on how much elements you want + 'id' can only be assigned with a unique identifier, while 'class' can have multiple identifiers... If you use same id on many elements, then that's you rather need to make it become a class... because it's better suited, and would avoid bugs, as most function designed for use id will only select the first element with this specific id, in addition to broke the logical/semantical meaning of the source code ;P
4th Sep 2017, 10:48 AM
visph
visph - avatar