简体   繁体   中英

How to select leaf node using jQuery :contains selector?

I want to get leaf elements containing specific text, and I used :contains selector. However, this selector selects includes every parent nodes too. Here is my example.

<div id='parent1'>
    <p id='target1'>Red balloon</p>
    <div id='target2'>Blue balloon</div>
</div>
<div id='parent2'>
    <span id='target3'>Brown balloon</span>
</div>

In this case, I just want to get elements containing text balloon . I expected to get 3 elements( target1 , target2 , target3 ) by $(":contains('balloon')") , but it returns every nodes including parent nodes of targets . (eg html , body , and every parent div )

How can I select only targets ?

Above HTML is only example. HTML以上只是示例。 HTML can be vary, so the answer should be generic.

  1. use indexOf("balloon") > -1 to find id the word balloon is found

 var arr = $("div").children().map(function(){ if($(this).text().indexOf("balloon") > -1 ) return $(this).attr("id") }).get(); console.log(arr) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='parent1'> <p id='target1'>Red balloon</p> <div id='target2'>Blue balloon</div> </div> <div id='parent2'> <span id='target3'>Brown balloon</span> </div> 

The solution below, look for all elements containing the word and clone these elements, This way we can be sure only to get "correct" amount of elements

Just remove .length and you have access to the elements.

 var s = $(":contains('balloon')").not("script").filter(function() { return ( $(this).clone() //clone the element .children() //select all the children .remove() //remove all the children .end() //again go back to selected element .filter(":contains('balloon')").length > 0) }).length; console.log(s) 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id='parent1'> <p id='target1'>Red balloon</p> <div id='target2'>Blue balloon</div> </div> <div id='parent2'> <span id='target3'>Brown balloon</span> </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