Houla Banada Houla Banada - 1 month ago 17
jQuery Question

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

Answer

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>

Comments