Is there a case insensitive version of the :contains jQuery selector or should I do the work manually by looping over all elements and comparing their .text() to my string?
相关问题
- Is there a limit to how many levels you can nest i
- How to toggle on Order in ReactJS
- How to fix IE ClearType + jQuery opacity problem i
- void before promise syntax
- jQuery add and remove delay
As of jQuery 1.3, this method is deprecated. To get this to work it needs to be defined as a function:
New a variable I give it name subString and put string you want to search in some elements text. Then using Jquery selector select elements you need like my example
$("elementsYouNeed")
and filter by.filter()
. In the.filter()
it will compare each elements in$("elementsYouNeed")
with the function.In the function i using
.toLowerCase()
for element text also subString that can avoid case sensitive condition and check if there is a subString in it. After that the.filter()
method constructs a new jQuery object from a subset of the matching elements.Now you can get the match elements in matchObjects and do whatever you want.
If someone (like me) is interested what do a and m[3] mean in Contains definition.
KEY/LEGEND: Params made available by jQuery for use in the selector definitions:
r = jQuery array of elements being scrutinised. (eg: r.length = Number of elements)
i = index of element currently under scrutiny, within array r.
a = element currently under scrutiny. Selector statement must return true to include it in its matched results.
m[2] = nodeName or * that we a looking for (left of colon).
m[3] = param passed into the :selector(param). Typically an index number, as in :nth-of-type(5), or a string, as in :color(blue).
A variation that seems to perform slightly faster and that also allows regular expressions is:
Not only is this case-insensitive, but it allows powerful searches like:
$("p:containsCI('\\bup\\b')")
(Matches "Up" or "up", but not "upper", "wakeup", etc.)$("p:containsCI('(?:Red|Blue) state')")
(Matches "red state" or "blue state", but not "up state", etc.)$("p:containsCI('^\\s*Stocks?')")
(Matches "stock" or "stocks", but only at the start of the paragraph (ignoring any leading whitespace).)What I ended up doing for jQuery 1.2 is :
This will extend jquery to have a :Contains selector that is case insensitive, the :contains selector remains unchanged.
Edit: For jQuery 1.3 (thanks @user95227) and later you need
Edit: Apparently accessing the DOM directly by using
instead of
In the previous expression speeds it up considerably so try at your own risk if speed is an issue. (see @John 's question)
Latest edit: For jQuery 1.8 it should be:
In jQuery 1.8 you will need to use