According to the documentation text() method returns a string containing the combined text of all the matched elements that it shows on your console, instead you need to iterate over them. Despite the fact that your condition is false, that does not work when the index is 0 ( 0 is a falsy value and all other integers are truthy values โโin Javascript), it should be .indexOf("t") > -1 .
$('span').each(function() { if ($(this).text().indexOf("t") > -1) console.log($(this).text()); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span>one</span> <span>two</span> <span>three</span> <span>four</span> <span>five</span> <span>six</span>
The easiest way is to use CSS :contains() pseudo-class selector and iterate over the elements using each() .
$('span:contains("t")').each(function() { console.log($(this).text()); })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span>one</span> <span>two</span> <span>three</span> <span>four</span> <span>five</span> <span>six</span>
UPDATE: You can use map() with get() to get as an array.
console.log($('span:contains("t")').map(function() { return $(this).text(); }).get())
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span>one</span> <span>two</span> <span>three</span> <span>four</span> <span>five</span> <span>six</span>
source share