Guide on finding the index of the clicked element based on its class

Is there a way to get the index of the clicked element within its list as well as in its .blue class?

I have successfully obtained the index within its list, but I am struggling to figure out how to get the index within its .blue class. For instance, when clicking on the 5th button, I want it to display 'index 4 - class index 3'.

Any suggestions or solutions?

$('.showindex').click(function() {
  var index = $(this).closest("li").index();
  console.log("index " + index + " - class index " + "?");
});
.blue {
  color: blue;
}
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>

<ol id="ol1">
  <li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
  <li><input type="button" value="Show index" class="showindex">showindex</li>
  <li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
  <li><input type="button" value="Show index" class="showindex">showindex</li>
  <li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
</ol>

Answer №1

If you want to achieve this functionality, simply target all elements with the class .blue and then find the index of the current element within that group.

Keep in mind that in JavaScript, indexes start at 0. So, the last button will display a 'class index' of 2. Give it a try:

let $blues = $('li:has(.showindex.blue)');

$('.showindex').click(function() {
  let $li = $(this).closest('li');
  let index = $li.index();
  let classIndex = $blues.index($li);
  
  console.log(`index ${index}, class index ${classIndex}`);
});
.blue {
  color: blue;
}
<script src="https://code.jquery.com/jquery-3.5.1.js" integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc=" crossorigin="anonymous"></script>

<ol id="ol1">
  <li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
  <li><input type="button" value="Show index" class="showindex">showindex</li>
  <li><input type="button" value="Show index" class="showindex blue">showindex blue</li>
  <li><input type="button" value="Show index" class="showindex">showindex</li>
  <li><input type="button" value="Show index" class="showindex blue">showindex blue/li>
</ol>

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 callback URL for signing in is malfunctioning within NextAuth

My navigation component displays "Sign In" and "Sign Out" based on the active session status. The issue I am facing is with the callback after signing in. Upon signing out, the button successfully redirects to the Home Page. However, after a successful si ...

jQuery does not pass data to bootstrap modal

I am currently working with the full calendar feature. Within this framework, I have implemented a modal that allows users to insert new events: <div id="fullCalModal_add_appointment" class="modal fade"> <div class="modal-dialog"> ...

What strategies can I use to refactor this controller in Angular 1.5 to make it more concise and efficient

I am encountering an issue with a component I have that contains a button. Whenever the button is clicked, it triggers one of two backend services depending on where the component is located. To achieve this, I am currently passing a flag to the component ...

Retrieve the input field's value with Selenium, verify its accuracy, and proceed to log a message to the console

Hey there! I'm facing a challenge while working with Selenium Webdriver, specifically Chrome Webdriver and writing tests in JavaScript. The problem is in a section of the code where I can't seem to grab the value typed into an input field using t ...

The controller in AngularJS fails to function properly after the initial page refresh

I am currently utilizing AngularJS in my hybrid Ionic application. Here is my controller: .controller('SubmitCtrl', function($scope) { console.log("It only works when the page is refreshed!"); }); The console.log function runs perfectly fine ...

One of my AngularJS directives seems to be malfunctioning while the rest are working fine. Can you help me troubleshoot

Recently, I've been immersing myself in the job search process and decided to create a website as a sort of online resume while also learning AngularJS. I enrolled in the Angular course on CodeSchool and am slowly building my website to my liking. (Pl ...

Cannot see the created item in Rails application when using RSpec, Capybara, Selenium, and JavaScript

Currently, I am in the process of developing a web store. The key functionality is already implemented where all products are displayed on one screen along with the list of ordered items. Whenever a product is selected for ordering, it should instantly app ...

Avoiding the capturing of events on $( document ).mousemove

Each time the browser detects a $( document ).mousemove event, my function is invoked. The performance is smooth with an empty page, but once I introduce a div element and hover over it, the function gets executed twice: first on the document and then agai ...

I am puzzled by the behavior of the $.getJSON request. I am uncertain about how to properly format the request with the callback=? parameter

Out of the three jQuery JSON requests, one is encountering cross-domain errors due to my lack of understanding how to include the callback=? parameter (or the reason why it signifies JSON vs JSONP). I am working on two requests to the same API; however, o ...

How can you set a predetermined value for a dropdown menu after populating it with data from a Django database?

I currently have a query in my Views.py file that is used to populate a dropdown menu. The query works properly, but I need it to display a specific value that is stored in a variable based on the user's selection. For example, let's suppose we ...

At the ready stance for a particular grade of students attending a class

I have created a page with a navigation menu that can be scrolled using the wheel mouse. My goal is to ensure that the li item with the 'selected' class is always positioned in the first position on the left. Is there a way to achieve this using ...

jQuery: Struggling with removing dynamically generated elements

Hey, I've hit a roadblock with this issue and can't figure out why it's not working. To give you an idea of what I'm trying to do, I've put together a jsfiddle: http://jsfiddle.net/ZNbm8/ This is my jQuery code: var count = 0; $ ...

Ways to verify whether the checkboxes within a gridview have been selected

enter code hereMy Gridview has five checkboxes in each row with options 'NO', 'YES', 'NA', 'NA/U', and 'REPEAT'. I am looking to enable a button if any of the checkboxes among 'NO', 'YES&apos ...

Is there a CSS4 resolution for transitioning from 0 to auto?

I searched extensively for information on CSS4, but unfortunately I came up empty-handed. Back in the era of CSS3, a common challenge arose when it came to height transitions from 0 to auto without relying on JavaScript. The introduction of transitions sa ...

What method does ajax utilize to retrieve data from the golang code?

I have developed a golang API to manage the data saved and retrieved from a form. Saving the data entered in the HTML form works fine, as it successfully saves the data in a MongoDB database. However, when retrieving the data based on the email entered in ...

Prevent cross-site scripting (XSS) when using vue toasted for displaying notifications

Whenever I include js code like "><img src=1 onerror=prompt(document.cookie);> in an input field and click submit, I use vue-toasted. The notification appears as shown in this image: https://i.sstatic.net/Gju9h.jpg and a popup shows the cookie in ...

Difficulty displaying background image on iOS devices like iPhone and iPad

Our Magento website has a background image that expands according to the content, working well on PCs and Macs. However, the white background does not show up on iOS devices. I have attached two screenshots - one showing how it appears on a regular PC bro ...

Issue with rendering in React Router

I've been having trouble with React Router in my code. I know that there have been changes from Switch to Routes in React Router Dom v6, but even after making the adjustment, my program just displays a blank screen. Can anyone help me resolve this iss ...

Avoid button wrapping in Bootstrap 4 navbar

Is there a way to make the search bar shrink on mobile view while keeping everything in line? Currently, the button is wrapping underneath the search bar. Check out the solution on JSFiddle body { margin: 10px; } .navbar-container { display: fle ...

The server received a GET request instead of a DELETE request

Currently, I'm facing a challenge in writing the frontend of an application. My goal is to implement a DELETE method using AJAX, but when I execute the code, Spring seems to be triggering a GET request instead. Here's the snippet of my HTML code ...