• 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:

  • Add, remove, toggle, and check for the presence of a class
  • Resize the width of a text box to fit its content automatically
  • Remove a Class from an Element
  • Get and Set Classes On An Element

Primary Sidebar

FREE UPDATES!

Get the latest updates in your inbox for FREE!

Popular Posts

Story Generator

IP Grabber

Simple Calendar

Remove Ads

Astrological Calculator

Copyright © 2022 JavaScriptSource.com

  • About
  • Privacy Policy
  • Submit
  • FAQ
  • Jobs For Developers
  • Contact Us