简体   繁体   中英

Can I use contains inside of a find in jQuery?

I have this html:

<table>
    <tr id="1"><td>test</td><td id="90">value</td></tr>
    <tr id="2"><td>another</td><td id="98">somthing</td></tr>
</table>

and this jquery:

  $("tr td:nth-child(2)").find(":contains('value')").each(function(){
        alert($(this).parent().attr("id"));
            });

I had assumed this would work, but it doesn't alert anything. If I remove the find portion it will alert with both values. Is there a way that I can include the find somehow?

Here is the fiddle:

http://jsfiddle.net/B4wMp/2/

Remove the .find() and move the :contains('value') to the selector

$("tr td:nth-child(2):contains('value')").each(function(){
  alert($(this).parent().attr("id"));
});

Fiddle: http://jsfiddle.net/B4wMp/5/

The correct way to do it is like this :

$("tr td:nth-child(2):contains('value')").each(function(){
alert($(this).parent().attr("id"));
    });

Why it wasn't working the way you had it written? Because from the first selector you get the td which has the word "value" in it and the td which has the word "something" in it. After getting that selection, running .find("...") on those elements starts looking for elements inside of what you currently have. Since both tds don't have any other element inside them, that .find() selector returns nothing.

You were using find but that's looking for children of the td elements that you've already selected. You don't have any children in your td elements.

You want to use filter or merge it into a single selector

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