How to Use ID and Class Selectors in HTML, CSS and jQuery

HTML elements are frequently labeled with an ID and/or class(es). ID and class names are not part of HTML syntax so many people are often perplexed by these attributes. What is the purpose of IDs and classes and how should they be utilized? IDs and classes are used to label HTML elements allowing them to be selected and formatted with CSS. Therefore they are called CSS selectors. CSS selectors are essential for tableless web design. However with the popularity of jQuery and the continual sophistication of Javascript CSS selectors are no longer exclusive to just CSS. jQuery also relies heavily on CSS selectors for its core functionality as well. In this tutorial I will explain the difference between IDs and classes and when to use one or the other in HTML and CSS. I will also show how to use IDs and classes with jQuery.

An element ID refers to a single unique element in the HTML document (DOM) while a class can refer to multiple elements that share the same qualities. For example there is only one element with the ID “header” in the DOM and that element encloses the header content of your page:

<div id="header">...</div>

Multiple elements that have rounded corners can be collectively labeled with the class “rounded”:

<div class="rounded">...</div>

Elements can only have one ID but they can contain multiple classes. Each class is separated with a space. You can use ID and class(es) concurrently as well:

<form id="contact" class="rounded wide">...</form>

IDs are referenced in CSS using the number sign:

#header { ... }
#content { ... }

Classes are referenced in CSS using a period:

.rounded { ... }
.wide { ... }

In CSS syntax it doesn’t matter how you utilize IDs and classes. The code may not be the most efficient but it will still work. It is up to the discretion of the developer to follow best practices. jQuery borrows from the same CSS syntax when selecting DOM elements as well. This is how you select IDs and classes in jQuery. Notice the use of the number sign for IDs and period for classes:

/* Selecting IDs */
$( "#content" ).html( "..." );

/* Selecting Classes */
$( ".rounded" ).html( "..." );

Multiple DOM elements can be selected in jQuery by separating each selector with a comma:

$( "#header, #content" ).html( "..." );

ID and class names follow the same syntax rules as variable names in most programming languages. They cannot start with a number or contain any special characters and spaces. Just like variable names ID and class names are generally case-sensitive as well. As a rule of thumb IDs and classes should also be named logically for the element that it is representing so that developers can understand and follow the code’s intentions.

You may also be interested in: