• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
JavaScriptSource

JavaScriptSource

Search 5,000+ Free JavaScript Snippets

  • Home
  • Browse Snippets
    • Addon
    • Ajax
    • Buttons
    • Cookies
    • CSS
    • Featured
    • Forms
    • Games
    • Generators
    • Image Effects
    • Math Related
    • Miscellaneous
    • Multimedia
    • Navigation
    • Page Details
    • Passwords
    • Text Effects
    • Time & Date
    • User Details
Home / CSS / Add a Class to an Element

Add a Class to an Element

Add a Class to an Element

To add a class to an element, you use the classList property of the element. Suppose you have an element as follows:

<div>Item</div>

To add the box class to the <div> element, you use the following:

const div = document.querySelector('div');
div.classList.add('box');

It’s possible to add multiple classes. The following adds three classes to the <div> element:

const div = document.querySelector('div');
div.classList.add('box','primary','rounded');

Source

https://www.javascripttutorial.net/add-class-to-an-element/

CSS

Related Snippets:

  • Get the Children of an Element
  • Apply a CSS animation to an element with JavaScript
  • Get and Set Classes On An Element
  • Toggle a class for an HTML element

Primary Sidebar

Popular Posts

Story Generator

IP Grabber – get a users IP address with JavaScript

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2025 JavaScriptSource.com

  • About
  • Privacy Policy
  • FAQ
  • Jobs For Developers