obtain the index of the parent element

Consider this snippet of code

<ul class='target'>
    <li><a>zero</a></li>
    <li><a>one</a></li>
    <li><a>two</a></li>
    <li><a>three</a></li>
</ul>
<ul class='target'>
    <li><a>zero</a></li>
    <li><a>one</a></li>
    <li><a>two</a></li>
    <li><a>three</a></li>
</ul>
<ul class='target'>
    <li><a>zero</a></li>
    <li><a>one</a></li>
    <li><a>two</a></li>
    <li><a>three</a></li>
</ul>

Here is the accompanying JavaScript:

$('ul.target li a').on('click', function() {
    var index = $(this).parent().index();
    alert(index);
    return false;
});

When clicking on an "a" element inside a "li", you will receive the index. However, how can you obtain the index of the middle (second) "ul" when clicking on the third "li" within the third "ul"? Is there a way to retrieve a different index other than the one clicked on?

EDIT

HTML code in the main file:


// Script details here

Within ajax.php:


// PHP script details here

Let me clarify again:

  1. In the main file, there is a table where clicks on "a" elements inside "td" within "tr.me_pega" are captured and sent to ajax.php.
  2. In ajax.php, a comprehensive response including additional JavaScript is sent back to be loaded into a predefined "td" within "tr.me_pega" (which can contain multiple instances).
  3. Back in the main file, after receiving the response from ajax.php, attempts are made to capture the parent index of "tr.me_pega" containing the "td" with a "select" element with values. If this explanation is confusing, please let me know.

Answer â„–1

To retrieve the previous ul element, utilize the .prev() method. Adjust the value of the index if it is less than 0 by setting it to "number of li elements - 1", and update $('ul.target li a') to $('.target'):

Check out the Fiddle here

$('.target').on('click', function() {
    var index = $(this).prev().index();
    index = index < 0 ? $('ul').length-1 : index;
    alert(index);
    return false;
});

If you prefer not to modify $('ul.target li a'), you can proceed with the following approach:

Access the updated Fiddle here

$('ul.target li a').on('click', function() {
    var index = $(this).parent().parent().prev().index();
    index = index < 0 ? $('ul').length-1 : index;
    alert(index);
    return false;
});

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

Filtering an array within an array based on user input

I am currently facing a challenge in filtering the child elements of an array. I am puzzled on how to specifically target children elements. So far, my filter is only functioning at the top level. Array: options: [ {name: 'Ð’Ñ‹Ñ…Ð ...

Is it necessary for a container component to always be connected to Redux?

As I prepare to embark on a new React project, I am reflecting on my past experiences to establish guidelines for structuring the application. Here are some principles that I hold true: Redux serves as the central repository for data in the entire appli ...

What is the best way to eliminate a duplicate item from the shopping cart without actually deleting it?

I developed an e-commerce platform with a cart feature using the context API. However, I encountered an issue where removing one item from the cart also deletes another item if there are two of the same items in the cart. How can this be prevented? Below ...

Sort the currency column in an HTML table through JavaScript

I have a code snippet below that I'm currently utilizing to arrange columns in an HTML table. The code works perfectly for alphabetical sorting and also for single-digit numbers. However, when attempting to sort a column containing currency values, t ...

Can JOLT be utilized to convert this HTML into a JSON output?

Is it possible to transform this HTML into JSON using JOLT SPEC? [<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final//EN"> <HTML> <HEAD> </HEAD> <BODY><br> #Message Receive correctly<br> ORDERID=1725786449 ...

Node.js server encountering issues with fs readFile not working, though it functions properly in the console

I am looking to display the content of my index.html file on my webpage. Below is the code in my server.js file: var express = require('express')(); const fs = require('fs'); express.get('/', (request, reponse) => { ...

A step-by-step guide to preventing multiple user logins from various tabs within one browser

In my application, it is built with the spring3 MVC framework. I am looking to implement a feature where if a user opens two tabs and tries to login simultaneously using different userIds, they will be redirected back to the same page. I want to achieve f ...

Unspecified content was received in the AJAX response

These are the two posts I am currently following: Ajax responseText comes back as undefined Can't return xmlhttp.responseText? Although I have implemented the code in the same way, I am encountering: "undefined is not a function" error message ...

The d3 selection's ID is currently not defined

When I try to select an element by its ID, I encounter the issue of it being undefined. To demonstrate this problem, I have created an example (fiddle link) The setup of elements is as follows: <pre id='output'></pre> <input id= ...

"Utilizing JQuery to Determine the Height of an iPad

I am currently creating a web application on the iPad in kiosk mode using the 320 and up framework. Although I am utilizing media queries, I have had to define the width and height of the page wrapper in pixels (1024 x 768 for landscape orientation on the ...

Choose a specific row from a table using an action button in PHP

I am currently working on a table that is being auto-populated from my database. Each row in the table has three action buttons - edit, delete, and view. I am using sessions to send the key value to the next page so that I can load the data of the select ...

Creating element modules in EJS

After building experience with React, I am now faced with the task of using ejs in my current project. Specifically, I need to return multiple radio elements. My attempt at achieving this was through the following code: <% const renderRadios = (value, ...

Creating a PHP script to generate a response for an AJAX request

I'm struggling with a logical issue in my script. The goal is to format some rows in a table without repeating the header, and then outputting all items as a variable passed to AJAX. However, I'm unsure of how to tackle this problem. function a ...

The notification bar only makes an appearance when necessary

I am currently working on a dynamic piece of code that sends a request to PHP and receives a response. The goal is for the notification bar to fadeIn() and fadeOut() every time there is a new notification. However, I have encountered an issue where the n ...

Combining data from multiple API calls in a for loop with AngularJS

I'm working with an API that contains pages from 1 to 10 and my goal is to cycle through these page numbers to make the necessary API calls. app.factory('companies', ['$http', function($http) { var i; for (i = 1; i < 11 ...

Method for transferring all items to a new array in AngularJs

There are 2 arrays: $scope.first = [ { fName:'Alex', lName='Doe' }, { fName:'John', lName='S' } ] var second= [ { fName:'Tom', lName='M', email:'<a href="/cdn-cgi/l/email-protectio ...

How to sort by a specific split part of an array using JavaScript and jQuery?

Looking to sort an array based on a specific split part of each element. example_array = ["Zebra:Add","Pay:Cold","And:Vets","Jam:Back"] The desired outcome is: console.log(code here) // prints ["Zebra:Add","Jam:Back","Pay:Cold","And:Vets"] Note: Each p ...

"Create visually appealing designs with Material UI by incorporating round images in Card

Recently delving into full stack development, I've been experimenting with coding to enhance my understanding of frontend using React JS and Material UI. In the process, I incorporated a card component to display posts from the backend. However, I enc ...

Leverage the power of EJS and Node JS by incorporating node modules into

I am having trouble importing my datetimepicker JavaScript and style sheet into my EJS file. Unfortunately, the CSS and JS files are not rendering properly when I run the code. Below is how my code is structured: In the EJS file: <html> <meta n ...

applying a margin to the cover div

I am currently working on a #cover element with the following CSS styling: #cover { background-color: #FFFFFF; height: 100%; opacity: 0.4; position: fixed; width: 100%; z-index: 9000; } The goal is to have it cover the entire visi ...