There is no such selector by default, but you can build your own, and filter
the things in the way you want.
How to add a new selector
jQuery.expr[":"]
is an object containing the available selectors (e.g. :visible
, :checked
and lots others). Here you want to add a new selector. So, in that case, the selector name will be the key, and the value will be a function receiving in the first argument the element.
If this function returns true
, the element is matched, otherwise (if it's false
), the element is not matched.
For example, this is the :checked
definition:
jQuery.expr[":"].checked = function (el) {
return el.checked === true;
};
Adding :containsExact
Simply, extend
or append directly the method in the jQuery.expr[":"]
object:
jQuery.expr[":"].containsExact = function (el, textToSearch) {
return el.textContent === textToSearch;
};
Example
// Add the containsExact selector
jQuery.expr[":"].containsExact = function(el, index, args) {
return el.textContent === args[3];
};
// Highlight the spans containing "Mars" in red
jQuery("span:containsExact('Mars')").css("background", "#F82125");
// Highlight "Hello World" in yellow
jQuery("span:containsExact('Hello World')").css("background", "#F5C700");
// Highlight the "Hello Mars" (without exclamation mark) in blue
jQuery("span:containsExact('Hello Mars')").css("background", "#0696DE");
span {
padding: 8px;
margin: 8px;
display: inline-block;
font-family: Arial;
font-weight: bold;
color: #293E51;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span><span>Hello</span> <span>World</span></span><br>
<span><span>Hello</span> <span>Mars</span></span><br>
<span><span>Hello</span> <span>Mars</span></span>!<br>
<span><span>Hello</span> <span>Mars</span>!</span>