• 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 / Replace a Class of an Element

Replace a Class of an Element

Replace a Class of an Element

To replace a class of an element with a new one, you use the replace() method of the classList property of the element:

element.classList.replace(currentClass,newClass);

Suppose you have a <div> element as follows:

<div class="primary info">How to replace a class in JS</div>

To replace the primary class with the secondary class, you use the following:

const div = document.querySelector('primary');
div.classList.replace('primary','secondary');

Source

https://www.javascripttutorial.net/dom/css/replace-a-class-of-an-element/

CSS

Related Snippets:

  • Get the Parent of an Element
  • Add, remove, toggle, and check for the presence of a class
  • Text Sections
  • Check if HTML element has class

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