$.extend(
$.expr[":"],
{
"containsNC": function (elem, i, match, array) {
return (elem.textContent || elem.innerText || "").toLowerCase().indexOf( (match[3] || "").toLowerCase() ) >= 0;
}
}
);
This code extends jQuery’s :contains
selector with a new case-insensitive version called :containsNC
.
The $.extend()
method is used to add a new property to the $.expr[":"]
object, which contains all of the custom selectors that jQuery supports.
The new property is an object with a single key-value pair, where the key is the name of the new selector (containsNC
) and the value is a function that takes four parameters (elem
, i
, match
, and array
).
Inside the function, the elem
parameter represents the current element being tested by the selector, and the match
parameter is an array of the matching parts of the selector.
The function uses elem.textContent
or elem.innerText
(depending on browser support) to get the text content of the element, converts it to lowercase, and checks if it contains the search string (which is the third item in the match
array). If it does, the function returns true
, indicating that the element should be included in the selector’s results.
This custom selector can be used like any other jQuery selector, for example: $("div:containsNC('search term')")
. This will select all div
elements that contain the text “search term”, regardless of case.
