An error occurs when trying to modify the classList, resulting in an Uncaught TypeError for setting an indexed property

I am attempting to modify the classes of multiple sibling elements when a click event occurs. Some of these elements may have multiple classes, but I always want to change the first class. Below is the code that I created:


let classList = event.currentTarget.classList;
if (classList[0] === 'open'){
  classList[0] = 'close';
  event.currentTarget.classList = classList;
  return;
}
let siblingList = event.currentTarget.parentElement.children;
for (let i=0;i<siblingList.length;i++){
  classList = siblingList[i].classList;
  if (classList[0] === 'open') {
    classList[0] = 'close';
    siblingList[i].classList = classList;
    break;
  }
}
classList = event.currentTarget.classList;
if (classList[0] === 'close'){
  classList[0] = 'open';
  event.currentTarget.classList = classList;
}

This function worked well when dealing with a single class and using className instead of classList. However, after switching to classList, it no longer functions as expected and throws the error message below:

Uncaught TypeError: Failed to set an indexed property on 'DOMTokenList': Index property setter is not supported.

Answer №1

When it comes to the property classList, it's important to note that it is read-only. This means you cannot assign a value to it directly, which can result in an error message like:

Uncaught TypeError: Failed to set an indexed property on 'DOMTokenList': Index property setter is not supported.

To work around this limitation, you should add or remove classes using specific methods. For example, to add a class:

event.currentTarget.classList.add('close')

If you need to remove a class instead:

event.currentTarget.classList.remove('open')

These methods simplify the process and eliminate the need to check for existing classes. Remember, attempting to remove a non-existent class will not cause an error.

Keep in mind, you can also use replace to swap one class for another:

event.currentTarget.classList.replace('open', 'close')

Answer №2

Check out this attempt!

let classes = test.classList;
    if (classes[0] === 'open'){
        test.classList.replace('open', "close");
      //event.currentTarget.classList = classes; // not necessary 
    }
    console.log( test.classList)
<div id="test" class="open b test"> <div/>

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

Next.js manages 0Auth authentication using MoneyButton for authorization

I have been working on implementing 0Auth user authorization for my Next.js application using the MoneyButton API. Successfully, I am able to initiate the authorization request with client.requestAuthorization('auth.user_identity:read','http ...

How to choose elements using jQuery according to their CSS properties?

Seeking a solution to a unique challenge I've encountered. The website I frequent has found a way to bypass my uBlock extension by using a script that generates random element classes, such as: <div class="lcelqilne1471483619510ttupv"></div& ...

Splitting up JavaScript and HTML within a WordPress environment

I recently came across a discussion on separating PHP code and HTML at this link I find myself in a similar predicament. My current project involves designing a WordPress website with numerous sliders, animated dropdowns, forms, and other components. The ...

Applying box-shadow to tables and collapsing borders with border-collapse property in IE!

The box-shadow property does not function properly in Internet Explorer when the table has a border-collapse: collapse style applied to it. ...

When a menu item is clicked, apply a class and change the display property to

I currently have an HTML menu with a submenu structured as follows: <li id="item-3" class="menu-item has-children-3"> <a href="#" class="sf-with-ul"><span>Auto</span></a ...

The issue with AngularJS 2-way-binding failing to refresh

Recently, I experimented with angularJS in conjunction with a range-slider-directive that can be found here: https://github.com/supertorio/angular-rangeslider-directive Initially, everything worked well while using the data-model solely within my HTML pa ...

Unable to execute JavaScript function by clicking

I've tried everything, but I can't seem to change the button text when selecting an item in the "Requirements" dropdown. You can view the issue on this site. Located at the bottom of the page is the "Requirements" dropdown. Each item has an oncl ...

Why can't the file upload button locate its CSS styles?

Check out this jFiddle demonstrating the issue. Some of the Angular code may appear broken in the example, but that's just due to it being pasted into jFiddle; it's not an actual problem I'm facing. The CSS styles aren't working on the ...

Issue: Headers cannot be set again once they have been sent during page reload

Whenever I attempt to refresh a specific page, I encounter an Error: Can't set headers after they are sent. Interestingly, when I click on a link to navigate to that page, the error doesn't occur. I have meticulously reviewed the sequence of even ...

Properly Positioning Text within React's Material UI Components

I am encountering a simple issue where I am trying to align '01/01/2020' with 'A00002'. To view my code on CodeSandbox, please visit CLICK HERE <div className={classes.root}> <Typography variant="h6" className={cla ...

Error: Docker/Next.js cannot locate module '@mui/x-date-pickers/AdapterDateFns' or its respective type definitions

When I run the command npm run build, my Next.js application builds successfully without any issues. However, when I try to build it in my Dockerfile, I encounter the following problem: #0 12.18 Type error: Cannot find module '@mui/x-date-pickers/Ada ...

Singling out a particular navigation tab

When attempting to link specific table IDs so that the corresponding tab is active when opened (i.e. www.gohome.com/html#profile), I am facing an issue where the active tab remains unchanged. Even after specifically calling out tab IDs, there seems to be n ...

Leveraging fullcalendar.io alongside JSONP

I'm currently in the process of integrating public holidays into my FullCalendar application. You can check out FullCalendar here. var actionUrl = @Html.Raw(Json.Encode(@Url.Action("Calendar", "Lecture"))); $('#fullcalendar').ful ...

When reducing the page size, the Bootstrap columns are colliding with

While resizing the screen, I noticed that these images are overlapping each other. I haven't made any changes to the css for container-fluid or row. <div class="container-fluid bg-grey"> <div class="row center"> <div class= ...

Is there a way to extract a particular value from a JSON URL and transfer it to a JavaScript variable?

I am looking to extract current exchange rates from a JSON URL for implementation in a webpage. Specifically, I want to retrieve a particular exchange rate (such as the US Dollar) and store it in a variable for use within a JavaScript function. Below is a ...

Conceal the Slider until Fully Loaded with Slick Slider by Ken Wheeler

I am currently using a slider function called Slick by Ken Wheeler. It is currently being loaded in the footer with just two variables. $('.slickSlider').slick({ dots: true, fade: true }); Currently, ...

Comparing Dates in Node.js using JavaScript and Sorting Arrays based on Date Values

Is JavaScript lacking a basic Date comparison feature similar to Python? Within my Node.js script, these lines are present: console.log(Date(2012,11,10) < Date(2012, 11, 9)) console.log(Date(2012,11,10) > Date(2012, 11, 9)) Surprisingly, both of t ...

Encountered a session.socket.io error: unable to find session using the provided key: connect.sid

So, I've been struggling with an issue for the past couple of days and I can't seem to figure it out. I've searched through various resources like this GitHub issue and Stack Overflow, but I still haven't found a solution. Here's m ...

The challenges encountered with JSONP/Ajax Script - displaying 'Undefined'

I need help retrieving data from a webserver that I don't have control over. I've searched online but haven't found a solution yet. I've tried various codes, with and without DataTables. If anyone could provide guidance on where to go ...

The constructor window.CCapture is not valid in Node.js environment

Can anyone help me figure out how to load CCapture in Node.js without using a headless browser for recording canvas stream? Every time I try, I keep running into the error message saying "window.CCapture is not a constructor." If you are familiar with the ...