Houla Banada
Houla Banada

Reputation: 77

jquery find previous class and return value

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();
      });

Upvotes: 2

Views: 304

Answers (2)

j08691
j08691

Reputation: 207901

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>

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337560

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>

Upvotes: 1

Related Questions