Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery to select elements based on the text inside them

How to select a tag having a specific text inside it and nothing else? For example if I have the following:

<table>
    <tr>
       <td>Assets</td><td>Asset</td>
    </tr>
    <tr>
       <td>Play</td><td>Players</td><td>Plays</td>
    </tr>
</table>

Is there any way that I may select the <td>Asset</td> and nothing else. I tried it with contains i.e. $("table tr td:contains(Play)") but it returns all the tds in the second tr (as it should). Whereas I just want <td>Play</td>.

Is there any way to achieve this, like there's a way to select elements based on their attributes. Is there any way to select elements based on the text inside them?

like image 978
Kamran Ahmed Avatar asked Nov 24 '25 13:11

Kamran Ahmed


1 Answers

How about that:

var lookup = 'Asset';
$('td:contains('+ lookup +')').filter(function() {
    return $(this).text() === lookup;
});

Demo

Try before buy

like image 139
insertusernamehere Avatar answered Nov 26 '25 04:11

insertusernamehere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!