Why does my 'click' event listener only work for the first two <li>'s and not the others?

I am new to programming and recently achieved success with my 'click' eventListener. When clicking on the first two li elements within the ul, the class of the div toggles on and off as expected. However, I encountered an issue where clicking on any li after the second one causes the class of every other div to toggle instead of the intended one. If you require further clarification, please feel free to ask.

As an example, let's say a for loop prints:

  • Bench Press
  • Deadlift
  • Squat
  • Shoulder press
  • Curl

If I click on 'Bench Press' and 'Deadlift', the .info will toggle and display their respective information. But when I click on 'Squat', it mistakenly toggles the .info for 'Curl' and so forth...

Below is all the code provided:

<div>
    {% for workout in workouts %}
    <ul>
        <li class="item">{{ workout.name }}</li>

        {% autoescape false %}
        <div class="info" id="info">
            <p>{{ workout.description }}</p>
        </div>
        {% endautoescape %}
    </ul>
    {% endfor %}
</div>
let li = document.querySelectorAll("li");
let info = document.querySelectorAll(".info");

for (let i = 0; i < li.length; i++) {
  li[i].addEventListener("click", function () {
    info[i].classList.toggle("info");
  });
}
.info {
  display: none;
}

Answer №1

Your javascript code is correct.

Ensure that your HTML is valid.

It's important to properly close each HTML tag so that the browser doesn't try to fix it for you, which could lead to misalignments with your <li> and <div> elements.

I noticed that you have made changes to your question, so this information may no longer be relevant.

Remember to debug and inspect the actual HTML interpreted by the browser. You can do this by right-clicking and selecting 'inspect' to view the current state of the browser.

let li = document.querySelectorAll("li");
let info = document.querySelectorAll(".info");

for (let i = 0; i < li.length; i++) {
  li[i].addEventListener("click", function() {
    info[i].classList.toggle("info");
  });
}
.info {
  display: none;
}

.info-colour {
  background: chocolate;
}

.item {
  margin-top: 1rem;
  background: orange;
}

p {
  margin: 0
}
<div>

  <ul>
    <li class="item"> workout.name 1</li>
    <div class="info info-colour">
      <p> workout.description 1 </p>
      <div>
        Necessary Workout Equipment: [Specific Machinery]
      </div>
    </div>


    <li class="item">workout.name 2</li>
    <div class="info info-colour">
      <p> workout.description 2 </p>
      <div>
        Necessary Workout Equipment: [Specific Machinery]
      </div>
    </div>


    <li class="item">workout.name 3</li>
    <div class="info info-colour">
      <p> workout.description 3 </p>
      <div>
        Necessary Workout Equipment: [Specific Machinery]
      </div>
    </div>

  </ul>
</div>

Answer №2

The value stored in the i variable at the end of the loop is retained, as it belongs to a separate callback function.

To address this issue, try implementing the following solution:

let listItems = document.querySelectorAll("li");
for (let j = 0; j < listItems.length; j++) {
  let item = listItems[j];
  item.addEventListener("click", function () {
    item.querySelector("div").classList.toggle("info");
  });
}

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

Types with conditions but no common parameter

I am looking to define my props as either type A or B. For instance export default function App() { type Checkbox = { type: "checkbox"; checked: boolean; }; type Dropdown = { type: "dropdown"; options: Array<an ...

Complete AJAX event: matching URL using regular expressions

After a specific ajax request is completed, I am attempting to execute a function. To target the desired request among multiple requests on the site, I am using settings.url as outlined in the official documentation: $( document ).ajaxComplete(function( e ...

Utilize axios-cache-interceptor to enforce caching of responses from axios

Is it possible to configure axios to always return a cached response with the help of axios-cache-interceptor? import axios from 'axios' import { setupCache } from 'axios-cache-interceptor' const axiosInstance = axios.create({ timeou ...

Steps to retrieve a file following an AJAX request

Is it possible to automatically download a file following an AJAX call? Currently, when I make the AJAX request, it redirects me to the resource instead of initiating the file download. This is the AJAX function I am using: $('.download').click ...

Find the location in a node.js script where a promise was rejected

Recently, I encountered a code snippet from an npm package that has been causing me some trouble. The issue is that I'm having difficulty in pinpointing where the rejected promise is being created or rejected within node.js. const someHiddenEvil = fu ...

Engage the PROTRACTOR refresh function

I'm just getting started with automation and Protractor. I successfully automated the login page, but now I'm facing a challenge with accessing a menu that I need in order to navigate to a different page. Within the menu, there is an href="#/dom ...

Using template expressions to access properties that contain spaces

Here is the code structure that I am working with: "name": { "age": [ { "data": { "how old": "23" } }, One of my JSON keys has a space in it. How can I access this pr ...

Having trouble with the rendering of the Stripe Element Quickstart example

Currently, I am diving into the world of Stripe's Element Quickstart. Take a look at this fiddle that I have been working on. It seems to be quite different from the example provided. Although I have included the file, I can't seem to figure out ...

Axios sending a 400 Bad Request to Django due to a missing required field

I'm having issues sending a POST request from my React frontend using Axios. import axios from 'axios' axios.post('http://server:port/auth/login', { username: 'admin', password: 'MY_PASSWORD', }, { ...

What is the method for displaying the value of a textarea?

I am relatively new to the world of coding, but I have already delved into HTML, CSS, and basic DOM scripting. My goal is simple - I want to create a comment box where people can leave messages like in a guestbook. However, when I input text and click on ...

Transferring information between Express and React through the Contentful API

I have embarked on a journey to explore Contentful's headless CMS, but I am encountering a challenge with their API client. My goal is to combine Express with React for server-side rendering, and I am utilizing this repository as my starting point. S ...

Bring in content using transclusion, then swap it out using AngularJS

I am looking to develop a custom directive that will transform : <my-overlay class="someOverlay"> <h4>Coucouc</h4> </my-map-overlay> Into : <div class="someOverlay default-overlay"> <h4>Coucouc</h4&g ...

What is a reliable method to retrieve the text from the current LI if all LI elements in the list share the

I'm encountering an issue with retrieving the text from LI elements because I have 10 list items and they all have the same class name. When I attempt to fetch the text using the class name or id, I only get the text of the last item. Here is my code ...

How do I incorporate Spotify into my mobile app to enable seamless background music playback?

Currently engaged in a mobile app project that utilizes react-native for the frontend and nodeJS for the backend. The main objective is to enable users to seamlessly play Spotify songs directly within the app, even in the background. This enhancement will ...

Load charts.js synchronously into a div using XMLHttpRequest

At the moment, there is a menu displayed on the left side of the page. When you click on the navigation links, the page content loads using the code snippet below: if (this.id == "view-charts") { $("#rightContainer").load("view-charts.php"); $(thi ...

Click to make the arrow come to life through animation!

I am brand new to coding and this is my inaugural code snippet: .container_menu { position: relative; top: 0px; left: 0px; width: 25px; height: 25px; } .container_menu .line-1 { background-color: black; width: 59%; height: 2px; positio ...

Node.js encountered an issue: Dependency 'mime-types/node_modules/mime-db' cannot be located

Recently, I followed a tutorial on creating a CRUD App with Nodejs and MongoDB. The project was completed successfully and everything was working fine. However, when I attempted to move all the files and folders to a new directory, disaster struck. Now, w ...

Exploring Selenium WebDriver: Manipulating Table Elements and Iterating Through Rows

Is there a more efficient way to iterate through tables row by row without using Absolute Xpath? In my test case, I need to search for specific data in each row. This was the previous logic of my code: private static int iRow; WebElement sWorkUnitRows = ...

Difficulties encountered when trying to load a URL or API that contains an array in javascript/p5js

I've run into a coding issue that I'm trying to troubleshoot in p5js. My goal is to retrieve data from a URL/API. The line `kursMin[1]...` gives the correct stock value, but the line `kursMin[i]` returns `[object Object]2021-03-124. close` Bo ...

Unable to execute jQuery function from JavaScript

I have been researching this issue and while I found similar posts, none of the solutions seem to work for me. My situation is slightly different. Within my code, I have a javascript function called addFormField that creates a dynamic input element within ...