I need to select an element based on its text in jQuery.
For instance:
this text
I know I can use .contain
You have some leverage with the :contains selector, but that only goes so far. You will need to further trim down the set of elements based on exact text matches, as in:
$("span:contains(this text)")
.filter
(
function()
{
return $(this).text() === "this text";
}
)
This makes the initial contains usage technically unnecessary, but you may experience performance benefits by starting out with a smaller collection of SPAN elements before filtering down to the exact set you're interested in.
EDIT: Took Ken Browning's suggestion to use the text()
function instead of innerHTML
for string comparison within the filter
function. The idea being that innerHTML
will capture text that we're not particularly interested in (including markup).