user3593405
user3593405

Reputation: 77

How to get value of parent of li in submenu with jquery?

I create submenu and I need to get value of direct parent for Submenu"li" this is my code

 <div class="box"> 

 <div class="col-sm-6">
 <!-- main menu-->
            <ul>
            <li class="m-sub">   

                   Cars
        <!-- sub menu for cars-->   
        <ul class="sub">
            <li> Audi</li>
            <li> KiA</li>
        </ul>
    </li>
                 <li class="m-sub">   

                    Tablets    
      <!--start sub menu for tablet -->
        <ul class="sub">
            <li>   Phone</li>
            <li>  Sony</li>
        </ul>
    </li>
    <li>  Laptop</li>
    <li>   Glass </li>

    </ul>
             </div>
         </div>

I need to get direct parent of sony for example, when I use ($(this).parent()).text() the result was phone not tablet. I need to get value of parent "tablet" ,when select Audi i need to get cars thanks in advance.

Upvotes: 0

Views: 586

Answers (1)

gyre
gyre

Reputation: 16777

Tablets isn't inside the direct parent of your list item; you'll need a bit more jQuery:

var li = $('.sub > li')

console.log(
  li.closest('.m-sub').contents().eq(2).text().trim() //=> 'Tablets'
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul>
  <li class="m-sub">
    <span><i class="icon-tablet"></i></span> Tablets <span class="leftarr"><i class="icon-chevron-right"></i></span>
    <ul class="sub">
      <li> Phone
      </li>
      <li> Sony
      </li>
    </ul>
  </li>
  <li> Laptop
  </li>
  <li> Glass
  </li>

</ul>

Upvotes: 1

Related Questions