liad idan liad idan - 5 months ago 48
jQuery Question

Jquery select li outside ul?

my code:

<ul class="categories">
<li class="category">
<a>category 1</a>
</li>
<ul class="subcategories">
<li class="subcategory">
<a>subcategory 1</a>
</li>
<li class="subcategory">
<a>subcategory 2</a>
</li>
</ul> <!-- tag should be closed here -->
<li class="category">
<a>category 2</a>
</li>
<ul class="subcategories">
<li class="subcategory">
<a>subcategory 3</a>
</li>
<li class="subcategory">
<a>subcategory 4</a>
</li>
<li class="subcategory">
<a>subcategory 5</a>
</li>
</ul>
</ul>


I want to get the text of the category when user click on the subcategory.
for example: click on "subcategory 2" give me the text "category 1"

Answer

$(document).on('click', '.subcategory', function(e){
	e.preventDefault;
  var text = $(this).parents('ul').first().prev().find('a').html();
  alert(text);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
<ul class="categories">
  <li class="category">
    <a>category 1</a>
  </li>
  <ul class="subcategories">
    <li class="subcategory">
      <a>subcategory 1</a>
    </li>
    <li class="subcategory">
      <a>subcategory 2</a>
    </li>
  </ul> <!-- tag should be closed here -->
  <li class="category">
    <a>category 2</a>
  </li>
  <ul class="subcategories">
    <li class="subcategory">
      <a>subcategory 3</a>
    </li>
    <li class="subcategory">
      <a>subcategory 4</a>
    </li>
    <li class="subcategory">
      <a>subcategory 5</a>
    </li>
  </ul>
</ul>

Comments