Home Change an element's class with JavaScript
Reply: 0

Change an element's class with JavaScript

user8183 Published in September 20, 2018, 1:14 pm

How can I change a class of an HTML element in response to an onClick event using JavaScript?

share|improve this question
  • 22
    "The class attribute is mostly used to point to a class in a style sheet. However, it can also be used by a JavaScript (via the HTML DOM) to make changes to HTML elements with a specified class." -w3schools.com/tags/att_standard_class.asp – Triynko Apr 7 '11 at 18:11
  • 6
    element.setAttribute(name, value); Replace name with class. Replace value with whatever name you have given the class, enclosed in quotes. This avoids needing to delete the current class and adding a different one. This jsFiddle example shows full working code. – Sandy Good May 18 '14 at 4:59
  • For changing a class of HTML element with onClick use this code: <input type='button' onclick='addNewClass(this)' value='Create' /> and in javascript section: function addNewClass(elem){ elem.className="newClass"; } Online – Iman Bahrampour Aug 22 '17 at 4:13

24 Answers 24

active oldest votes
up vote 3350 down vote accepted
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.47733 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO