admin管理员组文章数量:1302342
i have this basic html structure:
<div class=a>
<div class=m></div>
<div class=m></div>
</div>
<div class=b>
<div class=m></div>
<div class=m></div>
</div>
now i want to iterate over all m's but also would like to know if i am in a or b. using basic jquery syntax each i fail to do find this out.
$('.m').each(function(index) {
// how do i know if this m is part of a or b ?
});
i have this basic html structure:
<div class=a>
<div class=m></div>
<div class=m></div>
</div>
<div class=b>
<div class=m></div>
<div class=m></div>
</div>
now i want to iterate over all m's but also would like to know if i am in a or b. using basic jquery syntax each i fail to do find this out.
$('.m').each(function(index) {
// how do i know if this m is part of a or b ?
});
Share
Improve this question
edited Aug 26, 2011 at 14:47
Reporter
3,9485 gold badges35 silver badges49 bronze badges
asked Aug 26, 2011 at 14:45
clampclamp
34k75 gold badges207 silver badges305 bronze badges
7 Answers
Reset to default 8$(this).parent().hasClass("a")
or $(this).parent().hasClass("b")
if($(this).parent().hasClass('a'))
And same for b, it should work.
If you care, then I'd separate the selectors like this:
$('.a .m').each(function(index) {
// now I'm on .a items
});
$('.b .m').each(function(index) {
// now I'm on .b items
});
$('.m').each(function(index) {
this.parentNode.getAttribute( "class" );
});
For example, check the parent is .a
if($(this).parent().is('.a'))
You could use the .closest method:
var $this = $(this);
if ($this.closest("a").length === 1) {
alert("I'm in an a div");
}
else {
alert("I'm in a b div");
}
You can check the class of the parent element inside your function to identify if you are in 'a' or 'b'
$('.m').each(function() {
var parentClass = $(this).parent().attr('class');
});
So, the parentClass var should have a value of either 'a' or 'b'
本文标签: javascriptjQuery iterate over nested elements using eachStack Overflow
版权声明:本文标题:javascript - jQuery: iterate over nested elements using each - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741690918a2392717.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论