Explain Codes LogoExplain Codes Logo

How to add a class to a given element?

javascript
prompt-engineering
functions
performance
Anton ShumikhinbyAnton Shumikhin·Nov 6, 2024
TLDR
Here's a **one-liner** for adding a class to an element:

```javascript
document.querySelector('.my-element').classList.add('new-class');

Remember to replace .my-element with the correct element's selector and replace 'new-class' with the intended class name.

Constructive approach: add multiple classes

To apply multiple classes, you can add them simultaneously using the same add method:

element.classList.add('class1', 'class2', 'class3'); // Like a boss!

Double-check before adding: existence check

Before adding a class, it's wise to verify its existence. This helps prevent an operation equivalent to yelling in an empty room:

if (!element.classList.contains('new-class')) { // "Are you there, 'new-class'?" element.classList.add('new-class'); // "Okay, come in." }

Nostalgia for older browsers: legacy solution

For the nostalgia-tinged browsers like IE9 or earlier, which may not recognize classList, we have an alternative path:

if ('classList' in element) { // "Do you understand 'classList'?" element.classList.add('new-class'); // "Cool, join the club." } else { element.className += ' ' + 'new-class'; // "Alrighty then, let's do it the old way." }

Hook and fish: selecting the element

Before adding a class, we need to select the target element:

  1. Use document.getElementById('idName') when playing the 'name' game.
  2. Roll with document.querySelector('.className') when you want more thematic, CSS-style rules.

When you need to extend your fishing net to multiple elements, document.querySelectorAll is your best buddy:

document.querySelectorAll('.my-elements').forEach(el => el.classList.add('new-class')); // Because sharing is caring.

A stitch in time: safe and clean code

Let classList do the dirty work for you. It can handle class manipulations better than you manually tinkering with element.className.

Like diving headfirst into an empty pool, hastily appending classes could leave you in a mess:

element.className += ' ' + 'new-class'; // Err...mind the gap!

The 'Speed' demon: performance considerations

While JavaScript frameworks like Prototype, jQuery, and their ilk offer convenient methods to manage classes, the native JavaScript approach is faster than a Tesla on a racetrack.

Test out the top speed of different approaches on sites like jsPerf ⚡.

Reusable blueprint: writing a function

Consider crafting a reusable function to add classes. It's like a Swiss knife for all your class addition needs:

function addClass(element, className) { // We got a function here! if (element.classList) { element.classList.add(className); // Add that class! } else { element.className += ' ' + className; // Old school, but still cool. } }

And a reminder! Cross-verify your styles file. You don't want your styles stepping on each other's toes like unskilled salsa dancers.