Ways to identify the specific position of a class element in a sequence

Identifying the name of a class is simple enough.

event.target.className

However, determining if a specific element is the 3rd, 5th, or 11th one to use a particular class can be challenging, at least in my experience. I tried using the console (F12) to find a property that could help, but unfortunately, no luck.

In the following basic example, is there a way to identify whether the user clicked on ("box-a")[0], ("box-a")[1], ("box-a")[2], or ("box-a")[3]? I understand that individual IDs can be used for each element, but I want to keep this as simple as possible if it's technically feasible.

let count;

for (count = 0; count < 4; count++) {
  document.getElementsByClassName("box-a")[count].addEventListener("click", checker);
}

function checker() {
  document.getElementsByClassName("box-b")[0].innerHTML = event.target.className;
}

// event.target.className points to the class name, but what identifies [0], [1], [2] or [3]?
.box-a {
  background-color: green;
  border: 0.6rem solid black;
  padding: 10px;
  font-family: arial;
  font-size: 4rem;
}

.box-b {
  display: block;
  background-color: blue;
  border: .25rem solid red;
  padding: 10px;
  font-family: arial;
  font-size: 4rem;
}
<div class="box-a">Box 1</div>
<div class="box-a">Box 2</div>
<div class="box-a">Box 3</div>
<div class="box-a">Box 4</div>
<div class="box-b"></div>

Answer №1

As you iterate through the elements, make sure to attach an event listener to each box that will send the index of the clicked box to your checker function.

function checker(index) {
    // Utilize the index in any way you need
    console.log(index)
}

// Assign the same event listener to every element, ensuring the index is passed to the checker function
[].slice.call(document.getElementsByClassName('box-a'))
    .forEach(function(element, index) {
        element.addEventListener('click', function() { checker(index) })
    })
<div class="box-a">Box 1</div>
<div class="box-a">Box 2</div>
<div class="box-a">Box 3</div>
<div class="box-a">Box 4</div>
<div class="box-a">Box 5</div>

Answer №2

While this solution may not be optimal, it does get the job done.

// By clicking on any div element, you can see the output

document.querySelectorAll('.box-a').forEach((e) => { // Attaching event listener to all elements with class .box-a
  e.addEventListener('click', (event) => {
    var element = event.target;
    var index = Array.from(element 
      .parentNode // Get the parent node of the clicked element
      .querySelectorAll('.' + element.className)) // Selecting all sibling elements inside the parent node with the same class name as the clicked element
      .indexOf(element) + 1; // Finding the index of the clicked element and adding 1
    console.log(index);
  });
});

If you want to try it out in action, visit this link:

JSBin

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 test does not pass when attempting to use a shorthand operator to ascertain the truthfulness of

I've encountered an interesting issue with my unit test. It seems to work perfectly fine when I directly return true or false, but fails when I try to use a shorthand method to determine the result. Let's say I have a function called isMatched w ...

Is it possible to dispatch an async action when a route changes in React Router and Redux?

I am working on a universal react app with redux and react-router integration. My app has multiple routes such as: /2016 /2015 /2014 /2013 and so on. Each route requires fetching data from an API. Currently, I am using <Link> elements in the Navi ...

Using v-model with the Toast-UI editor in Vue.js adds a dynamic and

Is there a way to bind the input value while using toast-ui vue-editor since it doesn't support v-model? Here is my setup for toast-ui: import '@toast-ui/editor/dist/toastui-editor.css'; import { Editor } from '@toast-ui/vue-editor&apos ...

Conceal a specific character within a jQuery input field

I'm struggling to remove a dollar sign from an input field that is being filled with values from buttons. Even though the button populates the field, the dollar sign remains visible for some reason. Any assistance would be greatly appreciated. Thank ...

Explore by the anchor tag

I've recently implemented a search bar utilizing Bootstrap. This is the code for the search bar: <div class="md-form mt-0"> <input class="form-control" id="myInput" type="text" placeholder="Sear ...

The ng-submit() directive in Angular does not trigger submission when the "Enter" key is pressed in a text field

I have created a basic form using Angular where I want the ng-click function (updateMsg({name: name,room: room})) to be triggered when the user enters a value and then presses enter key. Unfortunately, the current code does not work as expected. The funct ...

Angular sorting data is not functioning as expected

I've been attempting to utilize AngularJS to organize my data, but unfortunately, it seems to be ineffective. I am fetching data from Firebase () and using Node.js to transmit it to a controller. Controller Code var myApp = angular.module('myA ...

Filter an array list using regular expressions

I'm attempting to sort through the following: Notify me if the current balance of this account exceeds $1. and eliminate this one: alertTypes = [ 'Alert me when this account’s available balance goes below $1.', 'Alert me when thi ...

Animated CSS sidemenu (utilized as a filtering panel for a table)

Hi there, I'm having some trouble with CSS Animation. I recently started developing websites and am using Bootstrap 4 along with Animate.css for animations. My goal is to have an icon button expand sideways to reveal a div containing select elements f ...

extracting an attribute from a class's search functionality

Let's consider the following HTML structure: <div id="container"> <div> <div class="main" data-id="thisID"> </div> </div> </div> If I want to retrieve the value inside the data-id attribute ...

Delete the subsequent element utilizing jQuery

Below is the HTML code snippet: <div name="taskNotificationsDiv"> <div class="notificationCard"> <span class="taskNotificationClose">x</span> Test </div> <hr> ...

Using ASP.NET to bind Page.Header.DataBind() can lead to conflicts with angular service method calls

I'm encountering a strange issue with my ASP.NET master page and code behind. Whenever Page.Header.DataBind() is called, all the public methods on my angular service are executed as well. Below is a snippet of my angular service: myModule.service("m ...

Tips on using MUI Texfield and Redux to update state

I am facing an issue with my input field as I attempt to pass some information before navigating to a different page. The problem lies in the fact that my Redux state is not updating, although the console confirms that the value is being passed correctly. ...

X-editable does not verify if the checklist values are checked

Hello everyone, currently I am working on a Laravel project where I have implemented the X-editable library for inline editing functionalities. I am facing an issue with updating a many-to-many relationship table (pivot table) and I am trying to use the X- ...

Retrieving cookie from chrome.webRequest.onBeforeSendHeaders

I have been developing a Firefox add-on with the goal of intercepting HTTP requests and extracting the cookie information. While I was successful in extracting the 'User-agent' data from the header, I faced difficulties when attempting to extract ...

Assign a unique HTML attribute to a child element within a Material-UI component

Currently, I am trying to include the custom HTML5 attribute "data-metrics" in the span element within the ListItemText Material UI component. However, I am facing some difficulty achieving this as per the specifications outlined in the Component API Docum ...

Can an open inventor scenegraph be transformed into a threejs scene?

Is there a way to display open inventor scengraph in a webgl format? I'm looking for some suggestions on how to tackle this project. Any ideas are welcome! ...

What could be causing the error I encounter when attempting to install axios?

While attempting to incorporate axios into my project, I used the command below: npm install axios However, an error has been persistently popping up: npm ERR! Unexpected end of JSON input while parsing near '...devDependencies":{"co' ...

What are some best practices for preventing unforeseen rendering issues when utilizing React Context?

I am encountering an issue with my functional components under the provider. In the scenario where I increase counter1 in SubApp1, SubApp2 also re-renders unnecessarily. Similarly, when I increase counter2 in SubApp2, SubApp1 also gets rendered even thou ...

Customizing a div's hyperlinks using JavaScript

I want to use JavaScript to change the appearance of a specific element's links. The CSS code would be: #element a:link { color: #000; } I am aware that you can modify the style of the element itself, like so: elementObject.style.color = ' ...