Remove all of the classes from the specified element using JavaScript

I have a button and I want to remove all the classes when it is clicked. Here is what I have tried:

button.style.className = ''

document.querySelector('button').onclick = function() {
  this.style.className = '';
}
.myClass {

  color:red;
  
}

.second {

  color:green;
}
<button class="myClass second">click me</button>

Since I don't know the names of the classes as they are dynamic, I cannot use classList.remove. How can I effectively remove all classes from an element?

Answer №1

It is not recommended to access className from the style object, instead access it directly like

this.className

document.querySelector('button').onclick = function() {
  this.className = '';
}
.myClass {

  color:red;
  
}

.second {

  color:green;
}
<button id="button" class="myClass second">click me</button>

Answer №2

Learn how to use the HTML DOM method called removeAttribute():

document.querySelector('button').onclick = function() {
  this.removeAttribute("class");
}
.myClass {
  background-color:blue;
}

.second {
  box-shadow: 0px 0px 5px 5px;
}
<button id="button" class="myClass second">click me</button>

Answer №3

Try using this.classname in place of this.style.className. Your updated Javascript snippet will look like this:

document.querySelector('button').onclick = function() {
    this.classname = ''; //removing the .style
}

Check out this demo on Fiddle.

Answer №4

To fix the issue, simply delete the (.style) part from the code and everything will function correctly.

 button.className = '';

Alternatively, you can also utilize this.className = "";

Both methods are effective in resolving the issue.

Answer №5

The following code snippet does the trick for me:

document.getElementById('targetElement').classList = null;

I haven't noticed any adverse effects when setting it to null in various browsers like Firefox, Brave, Safari, and Chrome.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Tips for creating a hover-activated dropdown menu

How can I create a drop-down menu in my horizontal navigation bar that appears when hovering over the Columns tab? The drop-down menu should include options such as Articles, Videos, Interview, and Fashion. To better illustrate what I am looking for, here ...

Tips for transforming list items into an array of strings

let typeList="[Product,Task,Invoice,Media,Store]"; I need to transform the string above into an array like this:- let typeList=["Product","Task","Invoice","Media","Store"]; Any help with this is greatly appreciated. ...

Connecting Ionic/Angular directives to scrollbars

I'm having an issue with my scrolling div: <div class="list"> <div class="item" ng-repeat="post in posts"> <img src="post.img" is-visible/> </div> </div> and I've implemented this directive: angular.elemen ...

How can ternary conditional operators be transformed into if statements?

When dealing with minified code like this, f&&!f.error?k.button.b==k.button.c.G?k.button.Q(b,e,f,c,d):k.button.b==k.button.c.o&&k.button.P(b,e,f,c,d):(console.error(f),f=f.error.message||chrome.i18n.getMessage("error_tooltip"),k.button.v(b ...

Is it possible to use HTML alone in Bootstrap 5 to link a button to display a toast notification?

I'm working on a Bootstrap page that includes a button and a toast element sourced from the Bootstrap documentation. The documentation states that I need to initialize the toast in JavaScript during page load. My goal is to have the toast appear when ...

New replacement for routerState.parent feature that has been deprecated in angular2

During my work with Angular 2 rc5, I encountered the following code snippet. this.router.routerState.parent(this.route).params.forEach((params: Params) => { url = params['url']; id = +params['id']; }); I had to resort to th ...

Changing HTML dynamically does not trigger the ng-click event within ng-bind-html

I have developed a custom directive that can display messages along with rendering HTML content that may contain Angular attributes like buttons, anchor tags with ng-click attribute, and more. index.html: <ir-error-panel status="status"></ir-err ...

What is the process for verifying a checkbox after it has been selected?

I simplified my code to make it easier to understand const [factor, setfactor] = useState(1); const [nullify, setNullify] = useState(1); const Price = 10; const Bonus = 15; const finalPrice = (Price * factor - Bonus) * nullify; // start ...

Create a randomized item for experimentation in NodeJs using an interface

Looking for a NodeJs package that can generate fake data in all required fields of a complex object described by a set of typescript interfaces, including arrays and sub-interfaces. Any recommendations? ...

Fullcalendar JS will easily identify dates with events, allowing users to simply click on those dates to redirect to a specific URL

When looking at the official example, we can see that the events are displayed in a typical calendar format: https://fullcalendar.io/js/fullcalendar-3.5.0/demos/basic-views.html Each event is listed in the calendar, and clicking on an individual event wi ...

Create an HTML table using data from a Python dictionary

Can anyone help me convert the dictionary below into an HTML table? {'Retry': ['30', '12', '12'], 'Station MAC': ['aabbccddeea', 'ffgghhiijj', 'kkllmmnnoo'], 'Download&ap ...

Items vanish when hovering over them

Creating nested links in the sidebar navigation bar with CSS has been a challenge for me. While hovering over main links, I can see the sub-links being displayed. However, when I try to hover/click on the children of the sub-links, they disappear. Note: M ...

The initial res.body object in NodeJS is enclosed in quotation marks

I've hit a roadblock while working on my social media website project using the MERN stack. Despite scouring the internet, I haven't been able to find a solution to the issue at hand. While following an online course, I encountered a problem tha ...

What is preventing ColladaLoader.js in Three.js from loading my file?

Recently, I decided to experiment with three.js and wanted to load a .dae file called Raptor.dae that I obtained from Ark Survival Evolved. Despite having some web development knowledge, I encountered an issue when trying to display this particular file in ...

Providing a user with a special discount tailored to their email address?

<script type="text/javascript"> function updatePrice() { var price = document.getElementById("product").value; var size_price = document.getElementById("size").value; var a=parseInt(price);//parsed type price var b=parseInt(size_price);//pa ...

Analyzing the structure according to the month/week/year

My array consists of count and date values: day = [ { count: 1, date: '2022-07-07' }, { count: 1, date: '2022-08-14' }, { count: 2, date: '2022-07-19' }, { count: 4, date: '2022-07-19' }, { count: 2, date: ...

What is the best way to submit several files along with additional fields simultaneously using FormData?

I have a collection called pocketbase that consists of fields like name, image, and order. My goal is to upload all the images with unique names and in parallel using the power of FormData. Take a look at my code below: export default function AddPhotosAd ...

Troubleshooting: AngularJS - Issues with nested controllers not functioning properly within ng-include

According to the AngularJS documentation (refer to nested controller fragment), I am attempting to implement nested controllers using ng-include Main.html <body id="spaWrapperApp" ng-app="spaWrapperApp"> <div class="container-fluid" id=" ...

Issue: Spaces are not being displayed between items in the @Html.DisplayFor statement within the Foreach

I have encountered a few similar queries on this platform and attempted the suggested solutions, but unfortunately, they did not resolve my specific issue. Within my view, I am using @Html.DisplayFor in a Foreach loop to display all GroupIDs in a particul ...

What is the best way to display an icon and text side by side in the header of a Phonegap app

____________________________________________________________ | logo_image page_Title | ------------------------------------------------------------ I am looking to create a header for my PhoneGap app similar to the one sh ...