2

I'm trying to get the closest dropdown-header when clicking a list item

<ul class="dropdown-menu">
  <li class="dropdown-header">Word 1</li>
  <li><a href="#">Click me 1</a></li>
  <li><a href="#">Click me 1</a></li>
  <li><a href="#">Click me 1</a></li>
  <li class="dropdown-header">Word 2</li>
  <li><a href="#">Click me 2</a></li>
  <li><a href="#">Click me 2</a></li>
  <li class="dropdown-header">Word 3</li>
  <li><a href="#">Click me 3</a></li>
</ul>

And this isn't working, could someone please explain. Thank you

$('.dropdown-menu').on('click', 'a', function(e) {
          $(this).parent().parent().find('.dropdown-header').html(); //would return Word #
          e.preventDefault();
      });
Houla Banada
  • 77
  • 1
  • 6
  • http://stackoverflow.com/questions/2310270/jquery-find-closest-previous-sibling-with-class –  Nov 04 '16 at 21:16

2 Answers2

1

closest() alone doesn't work for you in this case as it's intended to search for parents, not siblings of parents.

To fix this You could use closest() to get the parent li, then prevAll() with :first to get the element you're looking for. Try this:

$('.dropdown-menu').on('click', 'a', function(e) {
  e.preventDefault();
  var val = $(this).closest('li').prevAll('.dropdown-header:first').text();
  console.log(val);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu">
  <li class="dropdown-header">Word 1</li>
  <li><a href="#">Click me 1</a></li>
  <li><a href="#">Click me 1</a></li>
  <li><a href="#">Click me 1</a></li>
  <li class="dropdown-header">Word 2</li>
  <li><a href="#">Click me 2</a></li>
  <li><a href="#">Click me 2</a></li>
  <li class="dropdown-header">Word 3</li>
  <li><a href="#">Click me 3</a></li>
</ul>
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
1

You need to go up a level from the anchor to the list item, then up the list to the list item with the dropdown-header class. Also, .val() works for form elements, not list items, so you want .html() or .text(). Try:

var val = $(this).parent().prevAll('.dropdown-header').html();

$('.dropdown-menu').on('click', 'a', function(e) {
  var val = $(this).parent().prevAll('.dropdown-header').html(); //would return Word #
  console.log(val)
  e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="dropdown-menu">
  <li class="dropdown-header">Word 1</li>
  <li><a href="#">Click me 1</a></li>
  <li><a href="#">Click me 1</a></li>
  <li><a href="#">Click me 1</a></li>
  <li class="dropdown-header">Word 2</li>
  <li><a href="#">Click me 2</a></li>
  <li><a href="#">Click me 2</a></li>
  <li class="dropdown-header">Word 3</li>
  <li><a href="#">Click me 3</a></li>
</ul>
j08691
  • 204,283
  • 31
  • 260
  • 272