[英]How can I get the class of a parent element?
I would like to find the class
of the parent element of the child with .current
.我想用.current
找到子元素的父元素的class
。
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
但它总是让我undefined
NOTE: I don't know which a
currently has .current
which is why I have to use the .find()
method.注:我不知道哪a
目前有.current
这就是为什么我必须使用.find()
方法。
Your code should already work, but it might be more reliable to access the property className
instead:您的代码应该已经可以工作了,但访问属性className
可能更可靠:
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.我只是将找到的集合再次转换为 jQuery 对象。
See fiddle: http://jsfiddle.net/RaphaelDDL/wnW4u/见小提琴: http : //jsfiddle.net/RaphaelDDL/wnW4u/
Ps.: If more than one a
has class="current"
, only the first one will be retrieved. Ps.:如果有多个a
具有class="current"
,则只会检索第一个。
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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.