Using JavaScript, delete a class from an element

I am looking for a way to remove a specific class attribute from all elements on a webpage. The challenge is that I only have the class name as a reference, and cannot use any other identifiers like id or another class. Additionally, I cannot rely on JavaScript libraries to accomplish this task.

If anyone has suggestions on how to achieve this, please share them as it would be greatly appreciated.

It's worth noting that the class we are trying to remove will not appear more than twice.

Answer №1

In case you are using a modern web browser:

var forEach = Array.prototype.forEach;
var targetClass = "yourclass";

forEach.call(document.querySelectorAll("." + targetClass), function(element) {
    element.classList.remove(targetClass);
});

Refer to: forEach, querySelectorAll, and classList for more information.

Answer №2

function removeClassNames(name) {
    // changing the result into an Array object
    var elements = Array.prototype.slice.call(
        document.getElementsByClassName(name)
    );
    for (var index = 0, length = elements.length; index < length; index++) {
        var element = elements[index];
        element.className = element.className.replace(
            new RegExp('(^|\\s+)' + name + '(\\s+|$)', 'g'),
            '$1'
        );
    }
}

simply use it like this:

removeClassNames('target-class-name');

UPDATE: check out the live demo here: http://jsbin.com/eyuxur

Answer №3

This method may not be the most efficient on extremely large pages, as it loops through all elements to remove a specific class.

var elements = document.getElementsByTagName('*');
for(var j=0; j < elements.length; j++){
  elements[j].classList.remove('TargetClass');
}

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

VueJs: Finding the corresponding value of a data object

Is there a way to extract data from an object in Vue? This is the format of my data: datasets: [{ text:"Cars", value: "[1,2,3]" }, { text:"Trains", value: "[1,4,10] } ] When I receive information from route props like this: this.selectedText= this ...

Using jQuery cookies to dynamically change the body id during page loading

Is it possible to dynamically change the body ID during page load? I recently created an application that successfully changes the body ID. Now, I'm interested in detecting the body ID that I have already selected during page loading. Below is the c ...

What impact does the //g flag in Regex JavaScript have on the program's state?

I recently had a question that was answered, but I'm still trying to grasp why the regex behaves in a certain way. According to w3schools, it explains: g: Perform a global match (find all matches rather than stopping after the first match) Okay, ...

Using jquery to navigate back to the search results page

I am trying to figure out how to use jquery to return to the search results page, but my current code always takes me back to the main data instead of the search results. Can anyone help me with this issue? $(document).ready(function() { $("#kembali ...

Using iTextSharp in .Net to convert the action result into a downloadable pdf file via ajax

I have been successfully using iTextSharp to convert a razor view into a downloadable PDF via a C# controller. While the current implementation is functioning perfectly, I am seeking a way to transmit a model from a view to the PDF controller and enable th ...

The system encountered an error due to the absence of a defined Google or a MissingKeyMapError from the

Currently, I am developing a component that includes ng-map functionality by following the guidance in this tutorial. <div class="content-pane" map-lazy-load="https://maps.google.com/maps/api/js" map-lazy-load-params="{{$ctrl.googleMapsUrl}}"> & ...

Issue with updating state following data retrieval in React hooks

Recently, I've been experimenting with an API and working on a React application for data display. However, I encountered an issue while setting the state using the setState method of React Hooks after sending my information through a form request via ...

Experimenting with Chai in JavaScript to test an incorrect argument

Background: I recently delved into JavaScript and have been experimenting with it. It's possible that my question may sound silly, but I am eager to learn. I have developed a function called `getDayOfTheWeekFromDate` which returns the day of the week ...

Unveiling the Technique: Adjusting Field Visibility When Dropdown is Altered

I tried to find a solution on Stackoverflow for displaying/hiding a field based on dropdown selection using either jQuery or inline JavaScript. However, I am facing difficulties when implementing this within a table. Let's start with an easy approach ...

Fluctuate the window.location with jQuery or javascript

My goal is to create a functionality where clicking an image will toggle the window.location url between '#' and '#footer'. The current code I have for this is: <script> function clickarrow(){ var rd=Math.floor(Math.random() ...

Users are reporting that verification emails are not being sent when the Accounts.createUser function is used within

I have a simple meteor method set up to create user accounts. In my server/methods.js file: Meteor.methods({ createUserAccount: function(user) { return Accounts.createUser(user); } }); Then in my server/init.js file: Meteor.startup(function() ...

Guide on deleting an item from an object array in AngularJS

I have an array of objects and need to delete a specific object from it: var objectArray = [{"id":"John Doe","label":"John Doe","shape":"image","image":"app/data/img/user_icon.png","color":{"background":"#db630d","border":"#7c3400"},"level":0},{"id":"Java ...

Is it not possible to access a private member from an object that was not declared in its class...?

Within this program: class Example { #privateMember = 123; // these are fine addNumber (n) { return this.#privateMember + n; } doAddNumber (n) { return this.addNumber(n); } // "cannot read private member #privateMember from an ...

What could be causing this `even` function to malfunction when utilizing getElementById?

Need assistance with utilizing document.getElementById? Let's take a look at this code snippet: function even() for (i = 0; i < 10; i++) { if (i % 2 == 0) { alert(i); } } document.getElementById("even").innerHTML = i + &apos ...

Issue: Entering data in the input field for each row results in the same value being copied to the qty field

Currently, I have a field where users can enter the quantity for each row. Everything was functioning properly until I decided to add another input field for the pick option. Unfortunately, now it seems that whatever is entered in one field gets duplicated ...

Issue with setState not being triggered within axios POST request error handling block

I am in the process of setting up an error handler for a React Component called SignupForm.js, which is responsible for handling user registrations. Specifically, I am working on implementing a handler to deal with cases where a user tries to sign up with ...

AJV is failing to validate my body using the function generated by the compile method

Currently, in my API development process with express, I have implemented AJV as a middleware to validate the incoming body data. The version of AJV being used is 6.12.6 Below is the JSON schema named body-foobar.json: { "type": "object& ...

What is causing the extra space on the right side of the box?

I've been struggling to align text next to an image inside a box. Desired outcome CSS: #roundedBox { border-radius: 25px; background: #363636; width: auto; height: auto; margin: 10%; display: flex; position: relative; ...

Adjust the color of each list item depending on an array of strings

Within my perspective, I possess a collection of different statuses. <ul> <li>FIRST_STATUS</li> <li>SECOND_STATUS</li> <li>THIRD_STATUS</li> </ul> To continuously update the statuses in my contr ...

Developing an interactive Breadcrumb component using Vue.js in the latest version, Vue 3

Struggling to develop a dynamic Breadcrumb-Component in Vue.js 3. After hours of research, I haven't found a suitable solution due to outdated methods or lack of flexibility. As a beginner in frontend development, I am unsure about the best library to ...