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.
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>
This will work:
var currentli = $($('.nav').find('a.current')).parent().attr('class');
console.log(currentli);
I'm simply transforming the found collection into a jQuery object again.
See fiddle: http://jsfiddle.net/RaphaelDDL/wnW4u/
Ps.: If more than one a
has class="current"
, only the first one will be retrieved.
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>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.