The JavaScript indexOf method in an unordered list incorrectly returns the index of a specific event

Looking to retrieve the index number of an 'li' element within a 'ul' from the HTML structure. I attempted to convert the 'ul' into a list and access its children using:

[...ul.children]

However, upon targeting any of the children, I am receiving a -1 as the index instead of the correct index. How can this be resolved?

Could this issue be related to the presence of additional elements such as divs inside the list items?

Below is the JavaScript code snippet along with the corresponding HTML structure:

const ul = document.querySelector('ul');
ul.addEventListener('click', myFunc);

function myFunc(e) {
  const indexToShow = [...ul.children].indexOf(e.target);
  console.log(indexToShow);
  console.log(e.target);
}
<ul class="calendar-list">
  <li class="list-item">
    <div class="fight-link">
      <span class="date">1 Dec 2022</span>
      <span class="fighters-name">JAY</span>
    </div>
  </li>
  <li class="list-item">
    <div class="fight-link">
      <span class="date">2 Dec 2022</span>
      <span class="fighters-name">Jo</span>
    </div>
  </li>
  <li class="list-item">
    <div class="fight-link">
      <span class="date">3 Dec 2022</span>
      <span class="fighters-name">Bob</span>
    </div>
  </li>
</ul>

Answer №1

The click event is triggered by the span element, however, the comparison is made against the li element.

Therefore, in order to find the correct li element, you can use the closest() method to match the elements:

const ul = document.querySelector('ul');
ul.addEventListener('click', myFunc);

function myFunc(e) {
  const indexToShow = [...ul.children].indexOf(e.target.closest('li'));
  console.log(indexToShow);
}
<ul class="calendar-list">
  <li class="list-item">
    <div class="fight-link">
      <span class="date">1 Dec 2022</span>
      <span class="fighters-name">JAY</span>
    </div>
  </li>
  <li class="list-item">
    <div class="fight-link">
      <span class="date">2 Dec 2022</span>
      <span class="fighters-name">Jo</span>
    </div>
  </li>
  <li class="list-item">
    <div class="fight-link">
      <span class="date">3 Dec 2022</span>
      <span class="fighters-name">Bob</span>
    </div>
  </li>
</ul>

Answer №2

Let's take a look at the code below on how to accomplish this task:

const list = document.querySelector('ul');
  list.addEventListener('click', handleClick);

  function handleClick(event) {
    const itemIndex = [...list.children].indexOf(event.path[2]);
    console.log(itemIndex);
    console.log(event.target);
  }

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 process of transferring information from a form to mongodb?

I have created a nodejs project with the following structure: https://i.stack.imgur.com/JiMmd.png api.js contains: const express = require('express'); const router = express.Router(); const add = require('../model/myModel'); router.g ...

The number of articles in the MongoDB database is currently unknown

Currently, I am in the process of developing a blog using nodejs, express, and mongodb with jade as the template engine. The folder structure of my project looks like this: project/ modules/ views/ index.jade app. ...

Receiving an empty string from Chrome FileReader when dealing with large files (300MB or more)

Objective: The task is to read a file from the user's file system as a base64 string in the browser The size of these files can be up to 1.5GB Challenge: A script that works flawlessly on Firefox, regardless of the file size On Chrome, the script p ...

The specified type '{ songs: any; }' cannot be assigned to the type 'IntrinsicAttributes' in NEXTJS/Typescript

I am currently working on a straightforward script. Below is the index.tsx file for my Next.js application: import type { NextPage } from 'next' import SongsList from '../components/SongsList/SongsList' import { GetStaticProps } from & ...

Efficiently Extracting Data from an Array of Objects Using JQuery

What is the best method to extract information from the array below? How can I retrieve data categorized by specific categories? Is there a way to access only the key values? How do I retrieve just the data values? var main = [{ "key": "all", "dat ...

Navigate to a fresh webpage and find the scrollbar sitting at the bottom

When launching a new website using my forum system, I want the scrollbar to automatically be at the bottom so users don't have to scroll down. I'm not experienced in JavaScript and need help creating the code for this feature. ...

At times, the Ajax response may be lacking in content. However, the response tab in Google

My goal is to retrieve responses from an AJAX call and store them in the global scope for easy access throughout my website. var getOrderStatus = getOrderStatus(), getUserData = getUserData(), orderFormReady = $.when(getOrderStatus, getUserData), ...

Creating a mesh parallel to the xy-plane in Three.js

Looking to brush up on my CG fundamentals. How can I create a mesh (such as a circle) that is perfectly parallel to the xy-plane in the direction the camera is facing? For instance, I want it to be normal to the direction the camera is facing and not tilt ...

The value of the jQuery data on click event handler becomes 'undefined' when used within an AJAX handler

When I click on the Positive or Negative buttons, a jQuery event handler function is triggered. Each button passes different data objects to the handler. However, within the AJAX POST handler, I am unable to access the data from the click event. $('# ...

jquery toggle for partial visibility not functioning properly

Can jquery sliding functions be used to partially show and hide content? In this scenario, there is a list with 7 items but only the first two are visible initially, while the rest are hidden. The goal is to have all 7 items show when the user clicks to v ...

Issues encountered while trying to implement HTML text within span tags

In my code snippet, I am using a span element: <span> {textToRender} </span> The purpose of this code is to render HTML text (as a string) within a span element. some text <br/> some text <br/> some text <ol>text However, wh ...

Is it possible to maintain component data in Angular while also incorporating dynamic components?

All the code you need can be found here: https://stackblitz.com/edit/angular-keep-alive-component?file=src/app/app.component.ts Is it possible to maintain the state of entered values when switching components? I am currently utilizing dynamic component r ...

Utilize the power of React and Framer Motion to create a visually stunning fade

After creating a preloader that appears when the variable "loading" is set to true, I now want the loader to fade out. This is an overview of my files: On the home page with all the content: return ( <> {loading ? ( ...

What is the best way to assign a variable with the type (x:number)=>{y:number,z:number}?

I am trying to initialize a variable called foo, but my current code is not compiling successfully. let foo: (x: number) => {y:number,z: number} = (x) => {x+1, x+2}; This results in the following error: Left side of comma operator is unused and ha ...

How can I swiftly load or insert HTML code into an HTML file using jQuery?

I'm currently developing a mobile app using Cordova, essentially an html-based application running in an app wrapper. I have numerous elements and html code that need to be consistent across all pages, such as navigation menus, popups, and more. When ...

"Components in Pusher and Vue.js seem to be stuck in the channel even with Vue Router in

I've integrated Pusher with Laravel Echo to establish presence channels for specific areas within my application. All navigation on the front-end is managed through Vue Router. I'm facing an issue where Vue Router loads components based on route ...

Extension for Chrome - Personalized pop-up notification when page loads

I am looking to create a custom alert box that triggers on page load instead of the default one, which I find unattractive and possibly irritating for users. alert('hello'); My current approach involves the following code: manifesto.js "cont ...

Tips for creating a Carousel with more than three images using Bootstrap

Recently, I attempted to enhance my Carousel in Bootstrap by adding more images. Initially, I inserted the code snippet below within the ordered list with the class "carousel-indicators." <li data-target="#carouselExampleCaptions" data-slide-to=" ...

Execute supplementary build scripts during the angular build process

I've developed an Angular application that loads an iframe containing a basic html page (iframe.html) and a Vanilla JavaScript file (iframe.js). To facilitate this, I've placed these 2 files in the assets folder so that they are automatically cop ...

Trying to bring in components from directories above

I'm currently facing an issue with importing components from a parent directory into my project. My goal is to be able to use these components across multiple projects, which seems like the most straightforward approach. However, when I attempt this, ...