Difference between class and id attributes?

Hello! I have recently started the Basic CSS course and id attributes have been introduced. I’m curious about what the difference uses of classes, id attributes, and selectors(?) are. I know classes can be anchored into several elements and id attributes can only be anchored to one element. And forgive me if I am using the wrong terms, but why would you use an id attribute when you can just use a class or a selector? I have read that id attributes will be used in Javascript, is that what sets it apart from others?

selector ex: (I don’t know if that’s its official term)

p {
    font-size: 18px;
}`

Matter of style, for mere CSS reasons I always end up using classes because they’re reusable and composable (adding more than 1 class on the same element to add atomicity).

But when it comes to selecting an element in JS I always recur to ids (especially in forms, SPA containers like <div id="app"></div>, and canvas). Sometimes it’s useful to select multiple elements at once in JS and classes are more suitable for this.

1 Like

All of them, id, class, and selectors can be used in javascript to select your target element.

ID is the fastest in terms of performance. As you said, there should only be one ID but your webpage will still work if you manage to use the same ID in different parts of the page. However, javascript will stop searching after the first ID is found.

Selectors (without IDs or Classes) will be the slowest since the whole DOM will be searched to look for that matching selector.

Of course, if you need to select multiple elements, giving them a class name is the proper thing to do.

If you know there should only be one of that element, use an ID.

And let’s say you’re parsing an HTML/DOM string that was pulled/spidered from another website and need to select a particular data element (and the other website didn’t use a class or id in the element you want), then you may have to use css selectors to target the data that you want.


See this benchmark comparison about the different speed between search by id, class, and selectors.

https://jsperf.com/jquery-selector-speed-tests/98

2 Likes

Thank you for clearing things up! I guess it’s not as easy to tell the difference in the very beginning. I will keep working on it :smile:

Hi @emshark :grinning:

id attributes - The id attribute is a unique identifier which is used to specify the document. It is used by CSS and JavaScript to perform a certain task for a unique element.

class attribute - The class attribute is used to specify one or more class names for an HTML element. The class attribute can be used on any HTML element. The class name can be used by CSS and JavaScript to perform certain tasks for elements with the specified class name.

1 Like