This builds on Caspar's answer, but was too big for comments.
I thought it could be useful for others.
I used Caspar's solution but found that an empty string ""
is considered to exist in any string, see:
https://stackoverflow.com/a/18399216/1063287.
In my situation SuperSweetCheckbox
is a dynamic value and sometimes an empty string, in which case I don't want any matching logic to occur.
Creating a pseudo function using match()
seems to work, see:
https://stackoverflow.com/a/18462522/1063287.
You can also use filter()
, see:
https://stackoverflow.com/a/15364327/1063287).
Below is an example of the three variants - :contains()
, filter()
and a custom function:
jsFiddle
jsFiddle link
jQuery
var myString = "Test";
//var myString = "";
// 01. :contains() - matches empty string as well
$("ul li > label:contains(" + myString + ")").closest("li").addClass("matched").siblings("li").addClass("notmatched");
// 02. filter()
$("ul li > label").filter(function() {
return $(this).text() === myString;
}).closest("li").addClass("matched").siblings("li").addClass("notmatched");
// 03. custom function
$.expr[':'].textEquals = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().match("^" + arg + "$");
};
});
$("ul li > label:textEquals(" + myString + ")").closest("li").addClass("matched").siblings("li").addClass("notmatched");
HTML
<ul>
<li>
<label>Test</label>
</li>
<li>Oh Nu</li>
</ul>
CSS
.matched {
background: yellow
}
.notmatched {
background: aqua;
}