Javascript jQuery 查找所有类低于父级的元素,即使在子元素中

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/31409003/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:40:41  来源:igfitidea点击:

jQuery find all elements with class beneath parent, even in children elements

javascriptjqueryjquery-selectors

提问by Ben

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 .searchElbeneath the element .parent, even if they are within another child element, without searching the document globally with $(".searchEl")?

使用 jQuery/Javascript,我如何搜索和查找元素.searchEl下方具有 class 的所有元素.parent,即使它们位于另一个子元素中,而无需使用 全局搜索文档$(".searchEl")

回答by AmmarCSE

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>

回答by Anoop Joshi

Remove >from your select

>从您的选择中删除

$(".parent .searchEl").

You can use the .find()method also,

您也可以使用该.find()方法,

$(".parent").find(".searchEl")

回答by Tushar

>will select only direct descendants/children. Remove >to select all the descendant elements.

>将只选择直系后代/孩子。删除>以选择所有后代元素。

$(".parent .searchEl")

You can also use find()

你也可以使用 find()

$(".parent").find(".searchEl")