Using jQuery functions like closest(), find(), and children(), it is possible to target and retrieve the sibling of a specific parent

Having trouble determining the URL of a using .closest, .find and potentially other jQuery methods. The webpage structure is as follows:

ul
 ul
  ul.good
    li
    ...
    li
    li
      <a href="/findme">findme</a>
      ul
        .
         .
          .
          ul
           li
             a <-this

There are multiple nested lists on the page. I am trying to retrieve the href value of the a tag within the li element of the ul with class "good". The issue arises when I use closest() to find ul.good, as I then struggle to isolate the specific parent li element that contains this.

In essence, how can I extract the /findme value from a<-this? Is this feasible?

Just to clarify, the a href /findme occurs at the top level within ul.good.

a<-this is located much deeper within the structure (at an unknown depth).

Appreciate your assistance.

Answer №1

To begin, one approach is to first gather all the li elements that are children of the ul.good:

$goodUl = $this.closest('ul.good');
$lis = $goodUl.children();

Next, you can utilize these as parameters for the closest method:

$liParentOfThis = $this.closest($lis);

This will provide you with the parent $li, making it easy to then locate the a:

$a = $liParentOfThis.children('a');

While the above method is succinct, it may not be the most efficient since you are traversing up the chain twice. A potentially faster option involves using a loop:

$check = $this; 
while (($check = $check.parent().closest('ul')).length) {
  if ($check.is('.good')) break; // reached too high
  $a = $check.prev('a');
  if ($a.length) break; // found it 
}

In this iterative process, at each step, you move on to the next closest ul (as the parent is necessary for .closest search starting from the element itself) and verify if it has the desired previous sibling a. Once located, the search concludes.

Answer №2

Here's a quick and easy solution that should do the trick for you:

$("#here").on("click",function(){
   alert($(this).parents("ul.good").find("> li > a").attr("href"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <ul>
    <ul class="good">
      <li>something</li>
      <li>something</li>
      <li>
        <a href="/findme">findme</a>
      </li>
    <ul>
    <ul>
      <li>
        <a href="#" id="here">I am here</a>
      </li>
      </ul>
      </ul>
    </ul>
  </ul>
</ul>

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

Angular 17 | Angular Material 17.3.1: Problem encountered with Angular Material form field focus and blur event handling

I attempted to apply (blur) and (focus) effects to my mat-form-field input field, but it seems like they are not working properly on my system. Here is a code snippet that resembles what I am using: html file <form class="example-form"> ...

What is the best way to include a JavaScript variable within CSS styling?

I am currently implementing a dropdown menu system where the image of a parent div changes on mouse hover over a link, and reverts back when the mouse moves away. I have this functionality set up using a variable in my HTML code. Is there a way for me to m ...

Various background positions

Is it possible to declare multiple background positions for the same background image? I have a span with the class page_heading and I want this class to display the same image twice, once at the beginning of the text and once at the end. HTML: <h1&g ...

Adapting Bootstrap components based on the screen size: Viewport-driven

Check out our Custom Sizing Solution, designed to offer sizing options tailored to different devices and viewports. Here's what we can do: For small devices, the width will be set at 100% For larger devices, the width will be adjusted to 75% For ext ...

The appearance of online and local websites varies on a single screen and browser

My current dilemma revolves around the difference in appearance of my website when viewed locally versus online. Both versions are connected to the same git repository and use the same css file. Interestingly, I can view the page on both my local machine a ...

What is the best way to retrieve the input value from post.ejs?

app.js var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var passport = require('passport'); var localStrategy = require('passport-local'); var axios = require("axi ...

Creating Your Own Custom Select with DataTables

Hey there! I’m currently utilizing the tablesorter-plugin DataTables with serverside processing and ajax pipelining. Here’s a glimpse of my present serverside script: <?php // Database table being used $tabl ...

Display a popover by making an Ajax request

When attempting to display a popover on hover of an image, I encounter an issue where the content of the popover is not being shown. This content is retrieved through an Ajax call to a template, which includes a tag used in a taglib that renders the popove ...

Container contents are spilling out of control after adjusting container height to auto

I'm facing an issue on my webpage where the text overflows the container div, even after setting the height to auto. Here's how the page is structured: <html> <head> <body> <div id="wrapper"> <div id="inner_wrapp ...

Pattern to filter out numeric values from a collection

I want to apply a regex pattern to the <input> form element. The pattern should specify a range of numbers that are not permitted as input. For example, let's say I have a list of numbers like {1,4,10}, and any number other than these should b ...

Mastering Tooltip Placement Using CSS or JavaScript

I have been working on creating a CSS-only tooltip for a web application and so far I have managed to create some useful tooltips with different classes: tooltip-up tooltip-down tooltip-left tooltip-right The distinguishing factors between them are t ...

Catching exceptions with jQuery Ajax

I'm facing a tricky issue with an exception that seems to slip through my fingers: //myScript.js.coffee try $.ajax async: false type: "GET" url: index_url success: -> //Do something error: -> //Do something els ...

Horizontal rule spans the full width of the content, appearing within an ordered list

Check out this example to see the issue with the horizontal rule not extending all the way across under the number. I've tried using list-style-position:inside;, but that interferes with positioning the number correctly due to the left image being flo ...

PHP Implementing real-time dynamic categories

I am working on a project where there are multiple items listed with unique IDs. Each item has corresponding data with the same ID. I want to use JQuery, JScript, and PHP to display options based on the ID of the selected item in real-time. Below is a snip ...

Chosen option from the Bootstrap drop-down menu

Struggling with two problematic input fields on my Bootstrap website... The first is a Bootstrap Typeahead input field: <input type="text" id="typeahead" name='name' placeholder='The name' class="form-control" data-provide="typeahe ...

Using jQuery to dynamically add one of two fields to a form

After successfully using JQuery to add a field to a form, I am now stuck on how to implement two add field buttons for adding different fields. Can anyone point me in the right direction? <html> <head> <title>jQuery add / remove textb ...

Failure to successfully transmit data from Ajax to PHP script

When I click on a button in my HTML page, I am trying to retrieve information from my PHP code, but it is not connecting properly. The front page displayed in index.php is as follows: <!DOCTYPE html> <html> <head> <link rel="styleshe ...

Calculate averages of an array and show them when the page loads using Vue

In my coding project, there is an array named products that follows this specific structure: { "_id": "150", "name": "Milk", "description": "Skimmed", "price": "10", "ratings": [ ...

To see website changes, refreshing with Ctrl + F5 is necessary in the browser

I have a simple website that uses only HTML and CSS. Whenever I upload new files to the site, they do not appear in the browser until I perform a hard refresh by pressing CTRL + F5. Does anyone have any suggestions on how to fix this issue? ...

Using the JQuery Library, you can implement two submit buttons that either open in a new tab or submit

I am facing a situation where I have a FORM containing two submit buttons. My requirement is that when the first button is clicked, the form should submit on the same tab. On the other hand, if the second button is clicked, it should proceed to open a new ...