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