简体   繁体   English

jQuery find()包括当前节点

[英]jQuery find() including current node

I would like to select elements with jQuery's find() method. 我想使用jQuery的find()方法选择元素。 This method searches the children of a node but it does not include the node itself which I want to be considered aswell. 此方法搜索节点的子级,但不包括我也要考虑的节点本身。 In the answer to this question they proposed to do it like this: 在回答这个问题时,他们建议这样做:

object.find('selector').addBack('selector')

It seemed to be a good workaround for me, but unfortunately this solution does not work with every selector. 对我来说,这似乎是一个不错的解决方法,但不幸的是,此解决方案不适用于每个选择器。 Assume I have some nodes 假设我有一些节点

<div class="someClass">
  <div></div>
  <div class="someClass">
    <span></span>
  </div>
</div>

and want to use the childselector '.someClass > *' (or a similar one that affects the current node and its descendants). 并希望使用子选择器'.someClass > *' (或影响当前节点及其后代的类似选择器)。 I expect to get the 2 div elements and the span , but I obvously only get the span element. 我期望得到2 div元素和span ,但是很显然,我只能得到span元素。

Does someone know a workaround or another method? 有人知道解决方法或其他方法吗?

Assuming you aren't worried about picking up sibling elements, you could begin your query from the parent of the node you started with. 假设您不担心拾取兄弟元素,则可以从开始的节点的父节点开始查询。 That will ensure that the node in question is included in the query. 这将确保所涉及的节点包含在查询中。

 const selector = '.someClass > *'; let $node = $('body > .someClass'); let $matches = $node.parent().find(selector); console.log($matches) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="someClass"> <div></div> <div class="someClass"> <span></span> </div> </div> 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM