Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get the class of a parent element?

Tags:

I would like to find the class of the parent element of the child with .current.

var currentli = $('.nav').find('a.current').parent().attr('class');  console.log(currentli);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>  <div class="nav">    <ul>      <li class="tab1">        <a href="#1" class="current">Welcome</a>      </li>      <li class="tab2">        <a href="#2">About</a>      </li>      <!-- and some lists more -->    </ul>  </div>

but it always throws me undefined

NOTE: I don't know which a currently has .current which is why I have to use the .find() method.

like image 292
supersize Avatar asked Jun 14 '13 13:06

supersize


People also ask

How do you find the parent class in Python?

Python issubclass() is built-in function used to check if a class is a subclass of another class or not. This function returns True if the given class is the subclass of given class else it returns False . Return Type: True if object is subclass of a class, or any element of the tuple, otherwise False.


1 Answers

Your code should already work, but it might be more reliable to access the property className instead:

jQuery(function($) {   console.log($('.nav a.current').parent().prop('className')); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script> <div class="nav">   <ul>     <li class="tab1">       <a href="#1" class="current">Welcome</a>     </li>     <li class="tab2">       <a href="#2">About</a>     </li>     <!-- and some lists more -->   </ul> </div>
like image 162
Ja͢ck Avatar answered Nov 11 '22 02:11

Ja͢ck