I am after documentation on using wildcard or regular expressions (not sure on the exact terminology) with a jQuery selector.
I have looked for this myself but have
$("input[name='option[colour]'] :checked ")
You can use the filter function to apply more complicated regex matching.
Here's an example which would just match the first three divs:
$('div')
.filter(function() {
return this.id.match(/abc+d/);
})
.html("Matched!");
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="abcd">Not matched</div>
<div id="abccd">Not matched</div>
<div id="abcccd">Not matched</div>
<div id="abd">Not matched</div>
Add a jQuery function,
(function($){
$.fn.regex = function(pattern, fn, fn_a){
var fn = fn || $.fn.text;
return this.filter(function() {
return pattern.test(fn.apply($(this), fn_a));
});
};
})(jQuery);
Then,
$('span').regex(/Sent/)
will select all span elements with text matches /Sent/.
$('span').regex(/tooltip.year/, $.fn.attr, ['class'])
will select all span elements with their classes match /tooltip.year/.
James Padolsey created a wonderful filter that allows regex to be used for selection.
Say you have the following div
:
<div class="asdf">
Padolsey's :regex
filter can select it like so:
$("div:regex(class, .*sd.*)")
Also, check the official documentation on selectors.
If your use of regular expression is limited to test if an attribut start with a certain string, you can use the ^
JQuery selector.
For example if your want to only select div with id starting with "abc", you can use:
$("div[id^='abc']")
A lot of very useful selectors to avoid use of regex can be find here: http://api.jquery.com/category/selectors/attribute-selectors/
I'm just giving my real time example:
In native javascript I used following snippet to find the elements with ids starts with "select2-qownerName_select-result".
document.querySelectorAll("[id^='select2-qownerName_select-result']");
When we shifted from javascript to jQuery we've replaced above snippet with the following which involves less code changes without disturbing the logic.
$("[id^='select2-qownerName_select-result']")