Select element by exact match of its content

julian picture julian · Mar 12, 2013 · Viewed 109.3k times · Source

All right, I wonder if there is a way to make the :contains() jQuery's selector to select elements with only the string that is typed in

for example -

<p>hello</p>
<p>hello world</p>

$('p:contains("hello")').css('font-weight', 'bold');

The selector will select both p elements and make them bold, but I want it to select only the first one.

Answer

T.J. Crowder picture T.J. Crowder · Mar 12, 2013

No, there's no jQuery (or CSS) selector that does that.

You can readily use filter:

$("p").filter(function() {
    return $(this).text() === "hello";
}).css("font-weight", "bold");

It's not a selector, but it does the job. :-)

If you want to handle whitespace before or after the "hello", you might throw a $.trim in there:

return $.trim($(this).text()) === "hello";

For the premature optimizers out there, if you don't care that it doesn't match <p><span>hello</span></p> and similar, you can avoid the calls to $ and text by using innerHTML directly:

return this.innerHTML === "hello";

...but you'd have to have a lot of paragraphs for it to matter, so many that you'd probably have other issues first. :-)