What's the best way to access all elements rather than just the initial one?

I'm currently working on implementing an accordion-style FAQ sheet, but I'm facing some issues. Right now, I can only get the first element to display the hidden content. Below is the JavaScript code I am using:

var arrowIcon = document.querySelector('.arrow-icon');
var hidden = document.querySelector('.hidden');

var answer = 'answer';

arrowIcon.addEventListener('click', function() {
  if (answer === 'hidden') {
    answer = 'answer';
    hidden.setAttribute('class', 'answer');
  }
  else {
    answer = 'hidden';
    hidden.setAttribute('class', 'hidden');
  }
});

Answer №1

To successfully add click listeners to multiple elements, you can utilize the querySelectorAll method and then loop through each element using a forEach function. It's important to note that querySelectorAll returns a nodeList rather than an array, so if you need to perform array operations, you will need to convert it into an array first.

Here's an example of how you can achieve this:

var arrowIcons = Array.from(document.querySelectorAll('.arrow-icon'));

arrowIcons.forEach(element => {
    element.addEventListener("click", (event) => {
        // Your custom code goes here
    });
});

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

Creating a Next.JS Link that opens a new tab for internal URLs while avoiding redirection to external URLs

Currently, I am working on a project component for my homepage that showcases a specific project. The goal is to have the entire component redirect to the project page when clicked, except when the user clicks on the GitHub icon. In that scenario, I want t ...

Exploring the possibilities of custom layouts for specific routes within the pages directory in Next.js

I am interested in incorporating layout-based routing within my project's pages directory. I want to find a way to have a specific file, like the _app.tsx, that can only affect the files located inside a particular folder. This setup would operate si ...

Unable to locate the accurate information

Every time I run the cycle, there should be a match with the specified parameters and the message "OK" should appear. However, I am always getting a result of "No". request( { url: 'http://localhost:5000/positions/get', metho ...

When utilizing a JQuery plugin for sliders, Dart does not function in the same way that traditional JavaScript does

Starting out with Dart for Front-End development has been a bit challenging for me. I am trying to incorporate a JQuery plugin called FlexSlider using the Js-Interop Dart Library. However, it's not functioning as expected compared to pure JavaScript, ...

Guide to centering a Material UI Table on a webpage

Is it possible to center the <Table> within a fixed width <div>, and have a scrollbar appear when the browser is resized, while maintaining the fixed width of the <Table>? Thanks in advance. This is my current setup: <div> ...

Keep the color of the clicked link consistent

I've been experimenting with keeping the color of a link when clicked, not just while the mouse is over it (so that if the mouse moves away from the link, the color will stay). For example, on this website, when you click on "Ask a question," the col ...

Exploring the incorporation of the elasticsearch javascript library within your Aurelia application

Transitioning from the angular realm to aurelia has been a learning experience. However, I've hit a roadblock trying to figure out how to integrate elasticsearch.js into my aurelia app. Does anyone have any tips on how to achieve this? Or perhaps a ...

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...

An effective way to determine the size of a browser through javascript

In an effort to enhance the responsiveness of a website, I have included the following code snippet on one of my pages: document.write(screen.width+'x'+screen.height); However, I am encountering an issue where the code displays my screen resolu ...

The sequence in which jQuery's bind() function is executed

Suppose I have two jQuery bindings like the following: $("input:checkbox").bind("touchstart",function(){ } and $(document).bind('touchstart',function(e) { } In this case, the input checkbox is part of the same document. My question is: Wha ...

Display/Conceal the UL subelement when selected

I've been struggling to toggle the visibility of some ul checkboxes when their parent is clicked. Despite my best efforts, I just can't seem to make it work! Could someone lend a hand in getting this functionality working? Essentially, I need th ...

Uncertainty arises when trying to understand the callback function supplied to the `addEventListener` method in JavaScript

Question: I was recently exploring JavaScript's native addEventListener function. Typically, we use it like this: js selectElement.addEventListener('change', (event) => { const value = event.target.value }); However, when studying the ty ...

Updating the dynamic site script to be compatible with the newest version of the jQuery library

After finding a script on http://css-tricks.com/dynamic-page-replacing-content/, I decided to edit it to suit my needs. Initially, everything worked perfectly with "jquery-1.4.4". However, when I tried using versions later than "jquery-1.5", the active cla ...

How to pass only the clicked element to the onClick function in React.js

I have several elements with the same className, and I want to add the className active to an element (with the className history-node) when it is clicked, in addition to its current className. However, I am facing an issue where the child elements of tha ...

Bootstrap 4 carousel rotation technique

I am utilizing a bootstrap 4 carousel to showcase 6 unique products that I offer. Adjacent to the carousel, there is a list of links representing each of the 6 products. My goal is to implement a feature where hovering over these links will navigate to th ...

Modify the icon in the header of MaterializeCSS Collapsible when it is opened

I'm struggling to figure out how to change the icon of a toggled collapsible element. I have been reviewing their documentation but am having trouble making it work as intended. $('.collaps_roles_permission').collapsible({ accordion: tr ...

Unwrapping Promises in Angular for Seamless Resolution

I recently started working with Angular and found myself in a large project. I encountered a simplified version of my code below: var beforeClose = function() { var closeDeferred = $q.defer(), a = $q.defer(), b = $q.defer(), c = $q.defer() ...

What measures can I take to restrict users from adding names that are already in the system?

In the handleSubmit() function, I am attempting to prevent the user from adding an existing user, but it doesn't seem to be functioning properly. Ideally, if the name being added already exists in the persons list, an alert should be triggered. EDIT: ...

Exploring the depths of a JSON data structure

Newbie Alert: I'm dealing with a JSON response that triggers a .on('click') function and it looks like this: {"1411939719-8696.jpeg":true} My goal is to delete a row in a table based on the source of the call, but for some reason, it&apos ...

Can WebDriver (HtmlUnit, Ruby bindings) be configured to bypass JavaScript exceptions?

When attempting to load the page, HtmlUnit throws an exception and crashes my test. caps = Selenium::WebDriver::Remote::Capabilities.htmlunit(:javascript_enabled => true) driver = Selenium::WebDriver.for(:remote, :desired_capabilities => caps) drive ...