Igor Petev
Igor Petev

Reputation: 607

How to get parent value of div a value

I have html code:

<div class="top-menu">
  <div class="dropdown dropdown-inline">
    <a class="btn btn-primary dropdown-toggle" id="info" data-hover="dropdown" data-animations="zoomIn zoomIn zoomIn zoomIn" aria-expanded="false" >INFO</a>
  </div>
  <div class="dropdown dropdown-inline">
    <a class="btn btn-primary dropdown-toggle" data-hover="dropdown" data-animations="zoomIn zoomIn zoomIn zoomIn" aria-expanded="false">MAINITEM <span class="carot"></span></a>
    <ul class="dropdown-menu dropdownhover-bottom" role="menu">
      <li><a>A</a></li>
      <li><a>B</a></li>
      <li><a>C</a></li>
    </ul>
  </div>

I need when i click on li element (A, B or C) to get value of MAINITEM. I have around 10main items on page and need to get this MAINITEM of value.

I try using:

$("a.btn.btn-primary.dropdown-toggle, ul.dropdown-menu.dropdownhover-bottom li a").on('click', function () {
  alert($(this).closest('.dropdown-toggle').find('a').text());
})

But i get empty result.

Upvotes: 0

Views: 39

Answers (2)

Pablo
Pablo

Reputation: 6048

The jQuery.closest() function only filters through parent elements. Since you are combining two different selectors you should use common parent for both both target elements. In your case the common parent is .dropdown.

Additionally you need to make sure you are filtering through the correct a element because .dropdown can have many anchor tags. In your case you can use a.btn.

Below is a working example with the changes suggested above.

$("a.btn.btn-primary.dropdown-toggle, ul.dropdown-menu.dropdownhover-bottom li a").on('click', function(e) {
  alert($(this).closest('.dropdown').find('a.btn').text());
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div class="top-menu">
  <div class="dropdown dropdown-inline">
    <a class="btn btn-primary dropdown-toggle" id="info" data-hover="dropdown" data-animations="zoomIn zoomIn zoomIn zoomIn" aria-expanded="false">INFO</a>
  </div>
  <div class="dropdown dropdown-inline">
    <a class="btn btn-primary dropdown-toggle" data-hover="dropdown" data-animations="zoomIn zoomIn zoomIn zoomIn" aria-expanded="false">MAINITEM <span class="carot"></span></a>
    <ul class="dropdown-menu dropdownhover-bottom" role="menu">
      <li><a>A</a></li>
      <li><a>B</a></li>
      <li><a>C</a></li>
    </ul>
  </div>

Upvotes: 2

Alaksandar Jesus Gene
Alaksandar Jesus Gene

Reputation: 6883

Use this

http://jsfiddle.net/o90wnmuL/

 jQuery(".dropdown li a").click(function(){
   text =  jQuery(this).closest(".dropdown").find(".dropdown-toggle").text();
   console.log(text)
});

Upvotes: 1

Related Questions