0

I have the following UL LI list : -

<ul>
    <li><a href="#">item 1</a>
        <ul>
            <li><a href="#">item 2</a></li>
            <li><a href="#">item 3</a>
                <ul>
                    <li><a href="#">item 4</a></li>
                    <li><a href="#">item 5</a></li>
                </ul>
            </li>          
            <li><a href="#">item 6</a></li>
            <li><a href="#">item 7</a></li>
            <li><a href="#">item 8</a>
                <ul>
                    <li><a href="#">item 9</a></li>
                    <li><a href="#">item 10</a></li>
                </ul>
            </li>
        </ul>
    </li>
    <li><a href="#">item 11</a></li>
</ul>

What, using JQuery, is the easiest way to identify every single UL from one of the href links in one of the LI items?

For example, If i clicked on Item 9 or Item 10, I need to identify all the UL's going backwards from the one around the link back out to the outermost parent (but NOT including the parent).

I can only get it to find the closest to where I click so in the above example, clicking on Item 9 or Item 10 would only leave me at the first nearest UL, and not all of the UL's except main root/parent.

Thanks if anyone can help.

Dsamm

  • Here's a similar question which might get you what you need: https://stackoverflow.com/questions/3787924/select-deepest-child-in-jquery – dimiguel Jun 29 '20 at 01:16

1 Answers1

0
  • Use .parents() to get all the ancestors for a specific selector
  • Use .closest() to get the first ancestor (or self) for a specific selector

$("ul a").on("click", function() {
  const $a = $(this);
  const $UL_parents = $a.parents("ul");
  const $UL_closest = $a.closest("ul");
  
  console.log($UL_parents.length, $UL_closest.length)
});
<ul>
    <li><a href="#">item 1</a>
        <ul>
            <li><a href="#">item 2</a></li>
            <li><a href="#">item 3</a>
                <ul>
                    <li><a href="#">item 4</a></li>
                    <li><a href="#">item 5</a></li>
                </ul>
            </li>          
            <li><a href="#">item 6</a></li>
            <li><a href="#">item 7</a></li>
            <li><a href="#">item 8</a>
                <ul>
                    <li><a href="#">item 9</a></li>
                    <li><a href="#">item 10</a></li>
                </ul>
            </li>
        </ul>
    </li>
    <li><a href="#">item 11</a></li>
</ul>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Roko C. Buljan
  • 196,159
  • 39
  • 305
  • 313