简体   繁体   中英

jQuery find() including current node

I would like to select elements with jQuery's find() method. 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). I expect to get the 2 div elements and the span , but I obvously only get the span element.

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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