Encountering an Uncaught TypeError while trying to read properties of undefined (specifically 'remove') during a Change event is causing an issue for me

Looking to update the icons by changing the class from .fa-plus to .fa-minus for this specific menu section

<div class="accordion-menu">
                                <h2 class="accordion-header" id="subseccOne">
                                    <button class="accordion-button-m" type="button" >
                                        <i class="fa-solid fa-plus"  data-bs-toggle="collapse" data-bs-target="#subsecollapseOne" aria-expanded="true" aria-controls="subsecollapseOne"></i> <a class="item-section" href="">SEGUNDO NIVEL </a>
                                    </button>
...

<code>const icon= document.querySelectorAll(".fa-solid");
    const plusIcon = document.querySelectorAll(".fa-plus");
    
    
    for (i =0; i < plusIcon.length; i++){
        plusIcon[i].addEventListener("click", function (){
           
            icon.classList.remove("fa-plus");
            icon.classList.add("fa-minus")
        });
    }

Encountering an error in the console when running the click event on the function:

menu_funcionalidad.js:29 Uncaught TypeError: Cannot read properties of undefined (reading 'remove') at HTMLElement.

Answer №1

The reason for the error is because you have already assigned the variable icon to a nodeList, so when attempting to change the classes, icon does not refer to an individual element. To address this issue, I recommend using event.target to target and manipulate the specific element that has been clicked.

const iconElements = document.querySelectorAll(".fa-solid");
const plusIcons = document.querySelectorAll(".fa-plus");
    
    
for (let i = 0; i < plusIcons.length; i++){
    plusIcons[i].addEventListener("click", event => {
       event.target.classList.remove("fa-plus");
       event.target.classList.add("fa-minus");
       plusIcons.forEach(item => {
         if (item !== event.target) item.classList.add('//class-name');
       });
    });
}

Answer №2

When using document.querySelectorAll(".fa-solid"), you will receive a nodeList. This means that trying to access the classList within your loop will result in attempting to access the classList of a nodeList, which is not feasible.

If you wish to add/remove icons for each item in the node list mentioned above, you can iterate over the list using .forEach() method. (More information available <a href="https://developer.mozilla.org/en-US/docs/Web/API/NodeList/forEach" rel="nofollow noreferrer">here</a>).

To add/remove an icon from the element currently being iterated over, replace icon.classList... with i.classList.

If the latter option aligns with your intentions, consider implementing a check inside the loop like so:

for (i = 0; i < plusIcon.length; i++){
        plusIcon[i].addEventListener("click", function (){
            if (i.classList.contains("fa-plus")) {
                icon.classList.remove("fa-plus");
            } else {
                icon.classList.add("fa-minus");
            }                 
    });
}

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

What is the best way to use Python and Selenium to click on an angularjs link by comparing it to the text entered by the user?

A user can input a specific link that they would like to click. For example, if the user inputs "Tampa Bay Downs" for the variable track. In my Python Selenium test program, I will search for the following code: <a ng-click="updateFavorite()(raceInfo. ...

How can you check the boolean value of a checkbox using jQuery?

I have a checkbox on my webpage. <input id="new-consultation-open" type="checkbox" /> My goal is to store the state of this checkbox in a variable as a boolean value. consultation.save({ open: $("#new-consultation-open").val() }); Unfortunate ...

Steps to displaying a genuine Docx file within a Material CardMedia

Currently, I am facing an issue with positioning a docx file in my app. Interestingly, jpg and mp4 files are displaying correctly, but the docx file is not positioned as expected. If you want to try it out, simply open a doxc file. In the FileContentRend ...

Unable to execute application due to invalid element type

I'm just diving into learning React Native, and as I attempt to launch my app, an error message pops up: Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: object. Verif ...

What is the best way to incorporate multiple versions of jQuery on one webpage?

Is it possible to use multiple versions of jQuery on a single page? I need two different versions for various functions, but they seem to be conflicting with each other. If I implement jQuery noconflict, will the product scripts still work? <script typ ...

Tips on simulating the Q functions during unit testing in node.js using mocha and rewire!

Struggling with an issue while writing unit tests for node.js. The original code in my file is: var Q=require('q') . . . return Q.all(promises).then(function(data) { _.each(data, function(data) { checking.pu ...

Modify the starting URL in a Node.js application to /foo instead of just /

I am looking to visit a website with a default index URL like localhost:XXXX/foo, instead of the usual localhost:XXXX/. How can I achieve this specific setup? Any suggestions on how to make this happen? ...

What could be causing the delay in my IP camera image updates?

I have implemented a jQuery script to update the src attribute of an <img> element on a webpage at regular intervals. However, I am facing an issue where the image is not consistently updated according to the specified setInterval. Interestingly, dir ...

What is the best way to broadcast video content from Google Cloud Storage to iOS Safari?

Currently seeking a reliable method to serve videos through Google Cloud Storage that is compatible with all browsers, including Apple devices. I am facing challenges trying to play videos on my website (Vue front end, node.js backend) that are stored in ...

What are the reasons behind the unexpected behavior of the replace() method in the newest Safari update?

What is causing the JS method replace() to behave incorrectly in Safari version 11.1 when using "$<" in the second argument? For example: "aaaXXXbbb".replace(/XXX/, '_before_$<_after_') The actual result is: "aaa$<_after_bbb" The ex ...

Unravel JSON using JavaScript on the web

I encountered an issue while running this code and trying to decode it: var data = JSON.parse({"forms":[{"url":"example.com/example","name":"example"}]}) document.getElementById("name").innerHTML=data.forms.name Instead of the expected value, the returne ...

Internal VS External Stylesheets: What you need to know

I'm currently in the process of developing a website and I have started utilizing the style tag at the beginning: <!DOCTYPE HTML> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" ...

Exploring the challenges of applying styles to buttons using the :first-child and :last-child selectors, especially when

I successfully applied rounded corners to the first and last elements of a styled button using CSS. Here is how it looks: https://i.sstatic.net/A62Kl.png The issue arises when I dynamically insert new buttons using Angular's ng-if. The new buttons ...

Customizing the appearance of Jquery UI Accordion Headers

Trying to integrate the JQuery UI accordion into my JQuery UI modal dialog has been causing some alignment issues. Despite following code examples found online, such as http://jsfiddle.net/eKb8J/, I suspect that the problem lies in CSS styling. My setup i ...

Ensure you have the right zoom in and out percentages to properly test how your website responds on various browsers across different

Currently, I am using Google Chrome to test the responsiveness of a web application that I am developing. As of today, my browser versions are as follows: Google Chrome - Version 88.0.4324.96 (Official Build) (64-bit) Mozilla Firefox - Version 84.0.2 (64- ...

Building a Loading Bar with Two Images Using JavaScript and CSS

I am currently experimenting with creating a progress bar using two images: one in greyscale and the other colored. My goal is to place these two divs next to each other and then adjust their x-position and width dynamically. However, I'm having troub ...

What could be causing my Bootstrap 5 tabs to not switch when clicked?

Having recently delved into the world of HTML, CSS, and Bootstrap (version 5), I am embarking on a project to sharpen my skills. The goal is to recreate a website that features a tabbed section, along with other elements. Following a tutorial, I managed t ...

Is it better to store data individually in localStorage or combine it into one big string?

When it comes to keeping track of multiple tallies in localStorage, one question arises: Is it more efficient to store and retrieve several small data points individually or as one larger chunk? For example: localStorage.setItem('id1', tally1); ...

The CSS scale property is not working as expected when used in a React.js application, specifically

working environment ・next.js ・react ・typescript https://www.youtube.com/watch?v=ujlpzTyJp-M A Toolchip was developed based on the referenced video. However, the --scale: 1; property is not being applied. import React, { FunctionComponent ...

Created a custom function that includes a specific target href parameter

I have a website that implements role-based authentication, where the application displayed is dependent on the user's role. The code for this functionality is as follows: <asp:Repeater ID="ui_rprApp" runat="server" DataSourceID="odsApp"> ...