jQuery 如何获取父元素的类?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17109593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I get the class of a parent element?
提问by supersize
I would like to find the class
of the parent element of the child with .current
.
我想class
用.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
但它总是让我失望 undefined
NOTE:I don't know which a
currently has .current
which is why I have to use the .find()
method.
注意:我不知道哪个a
当前具有.current
,这就是我必须使用该.find()
方法的原因。
回答by Ja?ck
Your code should already work, but it might be more reliable to access the property className
instead:
您的代码应该已经可以工作了,但访问该属性可能更可靠className
:
var currentli = $('.nav').find('a.current').parent().prop('className');
回答by RaphaelDDL
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"
,只有第一个将被检索。