我有以下DOM树:
<div class="myclass">
<td>
// lots of td and tr elementds...
</td>
<div>
// lots of td and tr and div elementds...
.....
.....
<span class="myspan">
// lots of td and tr and div elementds...
.....
.....
</span>
</div>
</div>
我有几个主要的div元素 – div与class =“myclass”
$("div").each(function(i,e) {
if ($(e).hasClass("myclass")) {
// up to here i have all the div with myclass
.....
.....
//code should be added here
}
})
如何使用类myspan检索所有span元素 – 使用JQuery在主div元素中?
我想更清楚一点:
我需要的是一个元素列表,它具有class = myspan并位于当前div元素下,代码应该添加到我写的地方
因为每个div元素都有一组不同的元素.
我希望我现在能清楚自己.
请帮忙,
谢谢
解决方法:
这应该为你做到这一点.
$("div.myclass span.myspan").each(function() {
console.log(this);
});
编辑
保留父上下文的另一种方法是在下面的代码中显示.此更新基于对此答案的评论.我已经离开了原始答案(上图),就像原始问题的措辞一样,对于那些偶然发现这个答案的人来说,这可能是有用的.
$("div.myclass").each(function(i) {
console.log("spans within div index " + i);
$(this).find(".myspan").each(function() {
console.log(this);
});
});