Israelg99 Israelg99 - 1 year ago 114
jQuery Question

Select element by exact match of its content

All right, I wonder if there is a way to make the

jQuery's selector to select elements with only the string that is typed in

for example -

<p>hello world</p>

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

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

Answer Source

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. :-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download