Here is some sample HTML:
这是一些示例HTML:
<div class="parent">
<div class="searchEl"></div>
<div class="searchEl"></div>
<div class="child">
<div class="searchEl"></div>
<div class="searchEl"></div>
</div>
</div>
And here is a jQuery function:
这是一个jQuery函数:
$(function(){
$(".parent>.searchEl").each(function(){
$(this).html("Found this one");
});
});
The DOM elements will end up like so:
DOM元素最终将如下所示:
<div class="parent">
<div class="searchEl">Found this one</div>
<div class="searchEl">Found this one</div>
<div class="child">
<div class="searchEl"></div>
<div class="searchEl"></div>
</div>
</div>
Using jQuery/Javascript, how can I search for and find all the elements with class .searchEl
beneath the element .parent
, even if they are within another child element, without searching the document globally with $(".searchEl")
?
使用jQuery / Javascript,我如何搜索和查找元素.parent下面的类.searchEl的所有元素,即使它们在另一个子元素中,而不用$(“。searchEl”)全局搜索文档?
3 个解决方案
#1
9
Use a space instead of >
使用空格而不是>
$(function() {
$(".parent .searchEl").each(function() {
$(this).html("Found this one");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="parent">
<div class="searchEl"></div>
<div class="searchEl"></div>
<div class="child">
<div class="searchEl"></div>
<div class="searchEl"></div>
</div>
</div>
#2
2
>
will select only direct descendants/children. Remove >
to select all the descendant elements.
>将仅选择直系后代/儿童。删除>以选择所有后代元素。
$(".parent .searchEl")
You can also use find()
你也可以使用find()
$(".parent").find(".searchEl")
#3
2
Remove >
from your select
从您的选择中删除>
$(".parent .searchEl").
You can use the .find()
method also,
你也可以使用.find()方法,
$(".parent").find(".searchEl")
#1
9
Use a space instead of >
使用空格而不是>
$(function() {
$(".parent .searchEl").each(function() {
$(this).html("Found this one");
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="parent">
<div class="searchEl"></div>
<div class="searchEl"></div>
<div class="child">
<div class="searchEl"></div>
<div class="searchEl"></div>
</div>
</div>
#2
2
>
will select only direct descendants/children. Remove >
to select all the descendant elements.
>将仅选择直系后代/儿童。删除>以选择所有后代元素。
$(".parent .searchEl")
You can also use find()
你也可以使用find()
$(".parent").find(".searchEl")
#3
2
Remove >
from your select
从您的选择中删除>
$(".parent .searchEl").
You can use the .find()
method also,
你也可以使用.find()方法,
$(".parent").find(".searchEl")