What is the reason behind classList returning 'undefined' unless getElementById is explicitly used?

Why is it that I can't seem to select multiple elements with the same class (using querySelector, querySelectorAll, getElementsByClassName, etc) and use classList to check if just one div contains a specific class?

I've come across tutorials that show examples using getElementsByClassName as if they work flawlessly. However, in my case, when I try it on Firefox, I get an error:

Uncaught TypeError: document.getElementsByClassName(...).classList is undefined

I am assigning a CSS class of 'ontoggle' to these divs -

<div class="dot-container">
   <div class="dot-button" id="1" onclick="activateDot(this.id)"></div>
   <div class="dot-button" id="2" onclick="activateDot(this.id)"></div>
   <div class="dot-button" id="3" onclick="activateDot(this.id)"></div>
   <div class="dot-button" id="4" onclick="activateDot(this.id)"></div>
</div>

function activateDot(id) {
     if(document.getElementsByClassName('dot-button').classList.contains('db-active')) {
        console.log('bruh');
     } else {
        console.log('bruw');
     }
     document.getElementById(id).classList.toggle('db-active');
}

The workaround for me was to do the following -

function activateDot(id) {
   document.getElementById(1).classList.remove('db-active');
   document.getElementById(2).classList.remove('db-active');
   document.getElementById(3).classList.remove('db-active');
   document.getElementById(4).classList.remove('db-active');
   document.getElementById(id).classList.toggle('db-active');
}

Brrrr

Answer №1

When using getElementsByClassName, you receive a list of DOM nodes whereas obtaining an element by ID gives you just one element. To apply a desired class to each node in the list, it is necessary to iterate through them and add or toggle the class accordingly.

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

The absence of text is not displayed in an empty slot of a Buefy table

Currently, I am working on a Nuxt project with Buefy implementation. I attempted to create a table with an #empty slot that displays a message when no data is available. However, my code does not seem to be working as expected. If you refer to the Buefy do ...

What is preventing Firefox and IE from displaying images fully in a list item?

I am trying to create a slideshow with two separate sliders using li elements for that purpose. It works perfectly in Chrome and Safari, but I am encountering issues in Firefox and IE. In Firefox, the slideshow works fine in quirks mode but not in standar ...

Managing Chrome application authentication pop-up with Selenium Webdriver and C#

https://i.sstatic.net/lPbCv.png I have come across numerous discussions on this matter but none of the solutions seem to be effective. I am looking for a way to input the username and password into the chrome authentication alert using Selenium Webdriver ...

What is the best way to establish a maximum limit for a counter within an onclick event?

I'm struggling to figure out how to set a maximum limit for a counter in my onclick event. Can someone help me? What is the best way to add a max limit to the counter of an onclick event? Do I need to use an if statement? If yes, how should it be w ...

What is the process for triggering property decorators during runtime?

Wondering about dynamically invoking a property decorator at runtime. If we take a look at the code snippet below: function PropertyDecorator( target: Object, // The prototype of the class propertyKey: string | symbol // The name of th ...

Utilize a button within a form to add additional variables to a URL that already contains variables from a separate form

I operate a website that features a search bar and checkboxes for adding variables to the URL: term = "test" variable1=1 url/search?term=test&variable1=1 After completing the initial search, I have additional forms on the left side of the page with m ...

What is the best way to extract a specific line from a command using a child process in a Node.js environment?

I am attempting to retrieve the disk space of a virtual machine using a child process in Node.js. Below is the code I have written for this purpose: const { exec } = require('child_process'); function diskSpace(err, result) { exec('df - ...

Having trouble with gapi.client.request() not functioning properly?

I've been trying to use the Google API for freebase, and even though I'm following the correct call as per the documentation, it seems like there is an issue. The Chrome debugger is showing that something is wrong with this supposedly simple call ...

What steps can be taken to stop the page from refreshing and losing its state when cancelling navigation using the back and forward browser buttons in React-router v4.3?

I'm currently facing an issue with a page in which user inputs are saved using a react context object. The problem arises when a user navigates away from the page without saving their entries. I want to prompt the user to either continue or cancel, wh ...

Is it necessary to integrate the Facebook JavaScript SDK even if I do not plan on utilizing its features?

I have created some simple applications to use as custom tabs on my Facebook page, consisting of hyperlink images. I am not utilizing any of the functionality provided by the Facebook JavaScript SDK in these instances. Do I really need to load the Faceboo ...

Using jQuery's AJAX function to send a POST request and extracting data from the response

Below is the jQuery AJAX call that I am using: $.ajax({ method: "POST", url: "/Agenda/Template", dataType: 'json', data: { "templateId": templateSelect.options[templateSelect.selectedIndex].value }, c ...

Is there a way for me to gain access to alter the price function within Magento?

Now, I am faced with the task of customizing the discounted price for my Shopping cart. After some independent research, I discovered that by modifying the view.phtml and item.phtml files, I can properly display the desired price. However, I still feel uns ...

"Vanishing act: The mysterious disappearance of an empty JSON

After defining a JSON object and posting it to the backend (Node.js), there appears to be an issue. var imj = {}; imj.images = []; $.post("/image/uploadImages", imj, function(feedback){ ..... Unfortunately, when the backend received the data, the "images ...

Can you explain the process of utilizing CSS to create a smooth transition effect with

In the example application, I am utilizing the following plugin: I am perplexed by this line of code: style="width: 538px; transition: opacity 10000ms cubic-bezier(0.42, 0.65, 0.27, 0.99) 0s;. Can someone explain how the transition works? From what ...

The Angular Node server is responding with the error message "You have entered 'undefined' instead of a stream."

Using angular 9 + universal has been smooth sailing until I encountered an issue after building the app with npm run build:ssr and attempting to run it using node: node dist/app/server/main.js. The error message that popped up in the terminal was: Node ...

Internet Explorer causing trouble with reliable Ajax dropdown selection

There are two drop-down lists on my website, where the options in one depend on the selection in the other. The Ajax code works perfectly fine in Chrome and Mozilla, but it's not functioning correctly in Internet Explorer (specifically IE9). I need so ...

What could be the significance behind these sudden pop-ups of console error messages?

var sendTitle = function() { var title = $("input[name='movie-search-title']").val(); getMovie(title) getQuotes(title) } $("input[name='movie-search-title']").keydown(function(e) { if (e.keyCode == 13) { e.preventDefault(); ...

Activate divs with Bootstrap5 modal toggle functionality

What adjustments must be made to the Bootstrap 5 example below in order to achieve the following two objectives: The "afterAcceptingTerms" division should remain hidden until the user clicks on the Accept Terms modal button, ensuring that only the "before ...

Reload iframe content using a .php file within a different iframe

I am currently working on a page that consists of 7 different iframes: <iframe id="leftframe" src="structure/leftbar.php"></iframe> <iframe id="headerframe" src="structure/header.php"></iframe> <iframe id="menuframe" src="struct ...

"Is it possible to include a button for horizontal scrolling in the table

I have a bootstrap table with overflowing set to auto within its container, along with a locked first column. While a horizontal scroll bar allows for viewing additional data, I am looking to incorporate buttons for navigation as well. Users should have th ...