Posz
Posz

Reputation: 83

Grabbing specific anchor nested in lists

I'm having trouble grabbing certain text from an tag. I have the following code:

<ul class="listclass">
     <li>
          <ul class="subclass">
               <li><a href="#">Link 1</a></li>
               <li><a class="last" href="#">Link 2</a></li>
          </ul>
          <a href="#">Section Title</a>
     </li>
     <li>
          <ul class="subclass">
               <li><a href="#">Link 1</a></li>
               <li><a class="last" href="#">Link 2</a></li>
          </ul>
          <a href="#">Section Title</a>
     </li>
     <li>
          <ul class="subclass">
               <li><a href="#">Link 1</a></li>
               <li><a class="last" href="#">Link 2</a></li>
          </ul>
          <a href="#">Section Title</a>
     </li>
</ul>

So I simply want to be able to click on any "Link 1" and get the corresponding "section title" in that specific "li"

I've tried:

$('ul.listclass li a').click(function() {
if (!$(this).hasClass('last')) {
    var sectionTitle = $(this).closest('ul.listclass').find('a').text();
    alert(sectionTitle);
}
});

I just can't seem to grab that text because there isn't an association with it. And when I try to use it using "li" it just grabs "Link 1"

Upvotes: 1

Views: 52

Answers (1)

epascarello
epascarello

Reputation: 207511

.closest('ul.listclass').find('a').text();

is going to the top level, not the level you are at. You want to go up to subclass and look for the sibling of it that has the section title.

.closest('ul.subclass').next('a').text();

Upvotes: 2

Related Questions