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

  • Find all matching elements on a page with document.querySelectorAll()
  • Selecting an Element By Id
  • Remove a Class from an Element
  • Check if an element has an attribute

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