The removeClass method is not functioning correctly

I have implemented functions that enable users to select and deselect divs by clicking on them. However, I encountered an issue when trying to create a function that should deselect everything upon pressing a. Surprisingly, this function only deselects some of my divs instead of all. Here is the code snippet:

var divs = document.getElementsByClassName('fuori');
for(i = 0, j = divs.length; i < j; i++){
 divs[i].addEventListener('click', function(){
    if(!hasClass(this, 'selected')){
    this.className = this.className + " selected";
} else {
    removeClass(this, 'selected');
}
});
}

The 'removeClass' function looks like this:

function removeClass(ele,cls) {
    if (hasClass(ele,cls)) {
        var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
        ele.className=ele.className.replace(reg,' ');
    }
}

And here's the 'deselectAll' function:

function deselectAll(){
    var selected = document.getElementsByClassName('selected');
    alert(selected.length);
    for (i = 0; i < selected.length; i++){
        removeClass(selected[i], 'selected');
    }
}

While selecting and deselecting by clicking works smoothly, the issue arises when some divs are selected and then a is pressed, as it fails to deselect every div. How can I resolve this problem? And why does it occur in the first place?

Any assistance would be greatly appreciated!

Answer №1

Modify the for loop like this:

for (var i = selected.length; --i >= 0; removeClass(selected[i], 'selected'));

The result of getElementsByClassName() is a NodeList, not an array, and it's "live". This means that any changes to the DOM will also affect the list.

To avoid issues, iterate backwards. Another option is:

while (selected.length) removeClass(selected[0], 'selected');

Additionally, simplify your regex for removing classes:

function removeClass(ele,cls) {
    var reg = new RegExp('\\b' + cls + '\\b', 'g');
    ele.className=ele.className.replace(reg,' ');
}

In Javascript regex, \b denotes a word boundary. The hasClass() function is unnecessary as the replacement won't happen if the class string isn't present.

edit — A comment mentions that this method doesn't work with class names containing hyphens. To handle this, you can try:

function removeClass(ele,cls) {
    var reg = new RegExp('\\b' + cls.replace(/-/g, '\\b-\\b') + '\\b', 'g');
    ele.className=ele.className.replace(reg,' ');
}

or a similar approach.

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

Display a complete calendar with the date picker on a webpage

Currently experimenting with React to build a straightforward application. Admiring the appearance of full calendars from these date pickers (once clicked): Material-UI React-Toolbox Wondering if it's feasible to present the full calendar directly ...

What is the most effective way to condense these if statements?

I've been working on a project that includes some if statements in the code. I was advised to make it more concise and efficient by doing it all in one line. While my current method is functional, I need to refactor it for approval. Can you assist me ...

Find the first element in an array of resolved promises in sequential order

In my current setup, I am sending multiple requests to different APIs and each request takes a specific amount of time to fulfill. If one request is successful, I return the resolved value and stop. Currently, I am processing these requests one after the o ...

How to toggle checkboxes with jQuery

One issue I am facing is with a list of checkboxes within my Kendo grid. I have a select all option available as well. The problem arises when I select all checkboxes, then manually unselect some of them, and finally try to save the selection. The grid dis ...

Setting up xlsx for converting Excel spreadsheets to JSON format

Here is the command sequence I used to attempt the xlsx installation : sudo npm install xlsx npm install xlsx sudo npm install excel --save-dev npm install excel --save-dev However, after running each of these commands I encountered a consistent error mes ...

What are the best scenarios for utilizing a JSON body in a REST service POST request?

Is there a specific scenario when using a JSON body in a POST request for a REST service is ideal? At what point should someone consider utilizing a JSON body with multiple parameters/arguments? I have encountered a situation where I need to send a POST ...

Using a JavaScript script in my HTML alongside Vue.js is not possible

Hello there! I recently created a Node.js server and now I'm trying to display an HTML file that contains a Vue script which loads data using another method written in a separate JS file. However, when I attempt to load my HTML file in the browser, ...

The Vue JS task manager is unable to remove completed tasks from the list

I'm encountering an issue with the 'DELETE ONLY FINISHED' button. The goal is for this button to delete all finished tasks. When a task is completed, its 'finishedTask' property changes to true. I have attempted to store all finish ...

Display a Vue.js div element based on conditions matching a specific variable value

Is it possible for Vue.js to display a div only when a defined variable is set to a specific value? Currently, v-show="variable" can be used to show the div if the variable is set. However, I would like to know if v-show="variable=5" can be implemented t ...

The input text in the Typeahead field does not reset even after calling this.setState

As I work on creating a watchlist with typeahead functionality to suggest options as the user types, I encountered an issue where the text box is not resetting after submission. I attempted the solution mentioned in this resource by calling this.setState( ...

Tips on refreshing a div using jQuery while maintaining the functionality of addEventListener

Hi, I am facing an issue with updating the "div" element. The refresh works fine, but after refreshing when I try to click on the updated "div", the addEventListener in my JavaScript code does not seem to work anymore. Can someone please explain why this i ...

Ways to determine if an array with a mix of data types includes string values

Challenge I'm Currently Tackling: To solve this challenge, create a function named "findShortestWordAmongMixedElements". The task is to find and return the shortest string from an array that contains mixed element types. Important Notes: * In c ...

Tips for transferring the data from one yform value to another field

Within our online store, some products feature a yForm to consolidate various parts of the product. Is there a straightforward method to automatically transfer the sum field value to another field, such as the product quantity (which does not use yForm)? I ...

Guidelines for Naming Data Attribute Values in JavaScript

When it comes to the Data Attribute Value, should one use hyphens or camelCase as a convention? Hyphen Example: <input type="text" name="some_input" data-target="to-grab-input-via-javascript"> Camel Case Example <input type="text" name="some_ ...

Encountering [object, Object] while attempting to display JSON object retrieved from req.body in the console

While attempting to insert a product's details into my API's PostgreSQL database using Postman, I encountered an issue where the values of the specs key were displayed as [object Object] instead of showing the complete data. As a result, even in ...

Obscure all elements (images, text, divs, etc.) that appear after a div tag

Can you assist me with this issue? I have designed a static semi-opaque banner that remains at the top of a website. As the user scrolls through the website, all container objects move underneath the banner. I am looking to add a blurry effect to these ob ...

Filter Angular by columns that change dynamically

I have a filter function that works well when I use a static column name like this: this.listOfData = this.listOfData.filter((item: DataItem) => item.name.toLowerCase().indexOf(newValue.toLowerCase()) !== -1 ); Note: item.name However, I need to sea ...

After running JavaScript, retrieve the canvas data using the toDataUrl() method

After working on a Javascript function that creates a canvas and writes an image and text on it, I was expecting to get the base64 dataUrl. However, all I end up with is a blank canvas. Check out the code snippet below: function createBreadCrumb(label) ...

What is the method of accessing a function external to an extended function?

I came across this code snippet (function ($) { $.fn.CustomFunction = function (containerId) { let container = document.getElementById(containerId); let allFields = container.querySelectorAll("[is-required]"); ...

Is it possible to reference and assign controllers from templates in Angular 2 like in previous versions?

In my opinion, one of the great things about Angular 1 is that developers can write business logic in controllers without having to reference anything related to markup or rendering. After reading the Angular 2 documentation, I came across this code snipp ...