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

Exploring the concept of nested views in AngularJS's UI Router with multiple views integration

I am facing an issue with configuring multiple views on one page, where one view is nested within another. My code in app.js does not seem to be working properly. Below are the details: This is my index.html file <body ng-app="configuratorApp" > ...

How to send cross-domain AJAX requests to RESTful web services using jQuery?

I have been utilizing Jquery Ajax calls to access RESTful webservices in the following manner. The web service is being hosted on a different domain. $.ajax({ type: "GET", url: "url for the different domain hosting", crossDomain: true, ...

What is the reason that certain functionalities do not work on an element that has two CSS classes assigned to it

I have a unique situation with two input elements and a button: <input class="close-acc-usr opt-in" type="text" name="closeAccUsr" /> <input class="close-acc-pin opt-in" type="number" name="cl ...

Having difficulties with Smooth Div Scroll and Colorbox integration

Check out the gallery page by following this link: http://www.gerardtonti.com/Scrollable%20Gallery%2/index.html After trying numerous methods, I am still facing the same issue. Upon discovering your jQuery Smooth Div Scroll tool online, I intend to contr ...

Learn how to access an array within an object using JavaScript and an API URL

Trying to fetch data from the swapi API to display film titles using jQuery. Below is the JavaScript code: $(function(){ function promiseTest(){ return $.ajax({ type: 'GET', url: 'https://swapi.co/api/people/', } ...

Fascinating CSS rendering glitch observed on zooming in: all browsers create a noticeable gap between containers except for Firefox

I'm experiencing a rather intriguing and peculiar issue with css styles when zooming in and out on the browser. Specifically, I've created a material ui card where the background-color changes upon clicking with an animation effect. The animati ...

What is the best way to selectively print the contents of a child window upon page load?

I've created a function that opens a child window and fills it with content using AJAX. function OpenWindow(){ jQuery.ajax({ type: 'POST', data: { //some fields }, url: 'getPageForPrint.php', su ...

Reduce the transparency of the overlay picture

I have been utilizing the 'Big Picture' template to design a webpage. The overlay.png file adds a lighter background effect by overlaying intro.jpg with a partially transparent blue graphic. Despite my efforts to adjust the opacity and gradient/R ...

Changing the identification of elements

I noticed that when I open object X and Y, they have the same fields, tabs, and checkboxes. However, I am confused as to why the IDs of the checkboxes and other elements are different. Can you explain what gwt-uid(number) means? Please take a look at the a ...

Stop the time-dependent function from executing within a specific condition

Here is the code snippet I am currently working with: var w = $(window); var $navbar = $('.navbar'); var didScroll = false; w.on('scroll', function(){ didScroll = true; }); function AddScrollHeader(pxFromTop) { setInterval(fun ...

Incorporating Node.JS variables within an HTML document

After building a simple site using Express, I discovered that Node.js variables can also be used with Jade. exports.index = function(req, res){ res.render('index', { title: 'Express' }); }; This is the code for the index file: ext ...

TypeScript code runs smoothly on local environment, however encounters issues when deployed to production

<div> <div style="text-align:center"> <button class="btnClass">{{ submitButtonCaption }}</button> <button type="button" style="margin-left:15px;" class="cancelButton" (click)="clearSearch()"> {{ clearButtonCapt ...

Repeated Hover Effects on CSS Menu Icons

the webpage I need help with is (issue with general menu drop down) Hello I recently decided to enhance my menu by incorporating icons. I had successfully implemented a drop-down menu using only HTML and CSS, but when I attempted to add icons next to ea ...

Show information from table B following the selection made in table A

In my project, I need to retrieve and display data from the "foom" table once an option is selected from the "factory" table. The options in the select dropdown are populated with data from the "factory" table. The layout of the tables is as follows: Ima ...

How to move content without affecting the background of the `<body>` using scrolling

Can I achieve a glass morphism effect on my page without moving the background of the body? I only want to move the .container. Is this feasible? I attempted using background-attachment: fixed, but it did not work for me. Here is the code snippet I have be ...

Dynamically adjusting CSS Max-Height according to scroll position

Is there a CSS only technique to achieve the following scenario: An element is positioned absolutely at x,y coordinates on the screen. The document includes a vertical scrollbar depending on its content. Can the height of the element be adjusted based on ...

Is it possible to forecast an on click event using jQuery?

I have encountered a specific issue. Within my code, there are certain elements, specifically <li> elements, that undergo a particular operation triggered by a click event: $('.panelTabs li').on('click', function () { // ..som ...

Pop-up with a unique MediaBox design

Last week, I inquired about window pop-ups and have been brainstorming alternatives. One idea I had is to use mediabox/lightbox style pop-ups. Would it be feasible to create a link that opens a mediabox window off to the side when clicked? Users could dra ...

The custom styling in custom.css is not taking precedence over the styles defined in

My site is experiencing some element overwriting when I include css/bootstrap.min.css, such as 'a' tags, the .nav bar, and fonts used on the site. Load order: <link href="css/bootstrap.min.css" rel="stylesheet"/> <link rel="styleshe ...

Show the components only if the final digit in their identification number is less than i

I have several span elements with IDs like "tag1", "tag2", etc. I want to display only the spans whose ID ends with a number less than 19. These elements are part of a class called "notVis", which is hidden by default using $(".notVis").hide(); when the ...