Error encountered: Unable to assign a value to the property 'className' as it is undefined in JavaScript

Having trouble adding a classname to my JavaScript code which looks like so:

var a = document.querySelectorAll('.nav-tabs');
    for(var i=0 ; i<a.length; i++){
    a[i].addEventListener('click',function(){
        a[i].classList.add("active");
    });
}

An error message pops up saying Uncaught TypeError: Cannot set property 'className' of undefined and this is how my HTML appears:

<nav>
    <div class="container" id="container">
    <ul class="nav nav-tabs">
         <li role="presentation"><a href="#">a</a></li>
         <li role="presentation"><a href="#">b</a></li>
         <li role="presentation"><a href="#">c</a></li>
    </ul>
    </div>
</nav>

I would greatly appreciate it if someone could assist me in resolving this issue. Thank you very much.

Answer №1

let navTabs = document.querySelectorAll('.nav-tabs');
navTabs.forEach(tab => {
    tab.addEventListener('click', () => {
        tab.classList.add("active");
    });
});

Answer №2

When using addEventListener, the function you provide uses this to refer to the element itself. You can simplify it like this:

a[i].addEventListener("click",function(){
    this.classList.add("active");
});

In addition, it seems that you actually want to add the class to the li or a elements instead of the ul. Therefore, the selector should be:

document.querySelectorAll('.nav-tabs a');

You may also want to consider removing the active class from the previous element to avoid all elements ending up with the active class.

var a = document.querySelectorAll('.nav-tabs a');
a.forEach(function(e){e.addEventListener('click',function(){
        var active = document.querySelector('.active');
        active && active.classList.toggle("active");
        this.classList.add("active");
    });
});
.active{
  color:red;
}
<nav>
    <div class="container" id="container">
    <ul class="nav nav-tabs">
         <li role="presentation"><a href="#">link a</a></li>
         <li role="presentation"><a href="#">link b</a></li>
         <li role="presentation"><a href="#">link c</a></li>
    </ul>
    </div>
</nav>

Answer №3

Are you attempting to assign a specific class name to each <li> element?

You can achieve this by using the following snippet:

var elements = document.querySelector('.nav-tabs').children;
    for(var index=0 ; index<elements.length; index++){
      console.log(index)
      console.log(elements[index])
    elements[index].addEventListener('click',function(){
        this.classList.add("active");
    });
}

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

JavaScript glitch preventing fancybox functionality in Firefox browser

I'm experiencing an issue with FancyBox not working on Firefox while using js no conflict on this specific site Upon inspecting with Firebug, I encountered the following error: Error Line: 99 A similar error is also being thrown by Safari: Typ ...

Following its repair by my factory service, the data is now being shown complete with obvious HTML tags

After retrieving my data from a factory service in the form of a json_endoded array, I store it in a Javascript variable to be used as a template. When this template is displayed on a page, it appears with HTML tags intact: Some text here<br/><br ...

Adding the !important rule in React inline CSS effortlessly

Is there a way to include !important in my inline CSS property without disrupting the entire style? import React from "react"; export default class Todo extends React.Component { render() { const {text} = this.props; const cardStyl ...

Text input setting for jQuery UI Slider

Currently, I am utilizing jQuery UI sliders to input values in text boxes. However, I would like this functionality to be bidirectional; meaning if a value is entered into the text box, I want the slider to move to the corresponding position. I am unsure ...

Attempting to mark fields as required with asterisks using React Final Form in a React project

Is there a way to display an asterisk next to a label on a form using React Final Form? Here is what I have tried: <Field name="requestDescription" {...(<span style={{ color: 'red' }}>*</span&g ...

Encountering a 404 error with Angular 6 routing after refreshing the page when using an Nginx proxy

I currently have my angular application running within a docker container, exposed on port 83. Additionally, I have a separate spring-boot rest app running inside another docker container, exposed on port 8083. On the host server, there is an Nginx server ...

NodeJS closes the previous server port before establishing a new server connection

During my development and testing process, whenever I make changes, I find myself having to exit the server, implement the updates, and then start a new server. The first time I run the command node server.js, everything works perfectly. However, when I m ...

What is the CSS technique for applying a gradient background color to an HTML element from the bottom to the top?

I have successfully achieved the desired result from top to bottom using the code snippet below: /* I want to fill with a solid color, but in order to partially fill the background, I found that I needed to use a dummy gradient to achieve the desired ef ...

Utilize React-markdown to interpret subscript text in markdown format

I tried to create subscript text in an .md file using the following syntax: x_i x~i~ Unfortunately, react-markdown did not interpret this as subscript. After some research, I discovered the package remark-sub-super and implemented it with the plugin ...

Utilizing the correct method for binding checkboxes in Vue JS for effective two-way communication

I am working with data retrieved from a MySQL database where "1" and "0" represent boolean true and false. In my Vue component, I have set these values as shown below: data(){ return { form : { attribute_1 : "1", //attribute 1 is true ...

What is the method to group a TypeScript array based on a key from an object within the array?

I am dealing with an array called products that requires grouping based on the Product._shop_id. export class Product { _id: string; _shop_id: string; } export class Variant { variant_id: string; } export interface ShoppingCart { Variant: ...

How jQuery Mobile Navbar behaves with 4 elements instead of 5

I am currently experimenting with jQuery Mobile and I have come across a discrepancy. The documentation states that the navbar should wrap on five elements, but in my testing, it is wrapping at only four elements. Is this the expected behavior? Here is th ...

What is the best way to group Angular $http.get() requests for efficiency?

My challenge involves a controller that must retrieve two distinct REST resources to populate two dropdowns. I want to ensure that neither dropdown is populated until both $http.get() calls have completed, so that the options are displayed simultaneously r ...

Table within a table does not occupy full height within a table cell

I encountered an issue while nesting a table within a td element. The behavior differs between browsers: in Firefox, the nested table fills the entire cell from top to bottom, but in Edge and Chrome, it is centered within the td cell and does not occupy th ...

Learn the best way to send query parameters through the Next.js navigation router and take advantage of

Currently, I am implementing import { useHistory } from 'react-router-dom' const history = useHistory() ... history.push('/foo?bar=10') However, only the 'foo' part is being pushed into the url. What is the correct way to pas ...

Creating a structured layout with Bootstrap

I'm facing some confusion with the behavior of Bootstrap. This page suggests that for a 3x3 grid, one could use code similar to the following: <div class="container"> <div class="row"> <div class="col align-self-start"> ...

Patience is key when waiting for the outcome of an async Javascript function in order to obtain a result (Could it be

Hey there, I've been searching for a solution to my problem even though it's been discussed before. I'm trying to achieve something simple: creating a string like distance is : " + CalculateDistance(position);. The desired result should look ...

Reloading specific content on an ASP.NET CORE Razor Pages website

Hello, I am new to Razor pages and recently integrated the AdminLTE template into my Razor Page application successfully. In the _Layout.chtml file, I inserted the sidebar menu with anchor tags that link to specific pages, as well as the header bar and fo ...

"Vue is throwing an error because it cannot set the property '$offlineStorage' on an undefined object. How can this issue be resolved

While working on my vue ionic app, I integrated the plugin available at https://github.com/filrak/vue-offline. However, upon installing the plugin, an error was encountered: vue-offline.js?bf4e:193 Uncaught TypeError: Cannot set property '$offlineStor ...

Implement jQuery to toggle a class on click for added functionality

I am attempting to create a box that changes color when clicked. When the box is first clicked, it will turn red by adding the class red, and if clicked again, it will change to blue. The colors alternate with each click, but I am unsure of how to achieve ...