Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery wildcard selector

I want to select all the elements that have attribute starting with data-something-

For example

<span data-something-random="test">span 1</span>
<span data-nope="nope">span 2</span>
<span data-something-else="another test">span 3</span>

From the above example, I want to select span 1 and span 3.

I've tried

$('*[$data-validate]')

But it didn't work.

Alternative ways involving jQuery method instead of pseudo selectors are also welcome.

like image 477
rzr Avatar asked Jun 10 '26 10:06

rzr


1 Answers

I'd suggest:

$('*').filter(
    function(){
        var that = $(this),
            data = that.data();
        for (var a in data){
            if (data.hasOwnProperty(a)){
                return /^something/.test(a);
            }
        }
    }).css('color','red');

JS Fiddle demo.

Edited to offer a simple jQuery plugin that achieves the same, requiring you pass in a regular expression:

$.fn.hasAttrMatching = function (expr) {
    var reg, data;
    if (!expr) {
        return this;
    } else {
        if (typeof expr === 'string') {
            reg = new RegExp(expr);
        } else if (typeof expr === 'object' && expr.test) {
            reg = expr;
        }
        return this.filter(function () {
            data = $(this).data();
            for (var a in data) {
                if (data.hasOwnProperty(a)) {
                    return reg.test(a);
                }
            }
        });
    }
};

JS Fiddle demo.

This can be called as follows, using a literal regular expression:

$('body, body *').hasAttrMatching(/^something/).css('color', 'red');

Using a string representation of a regular expression:

$('body, body *').hasAttrMatching('^something').css('color', 'red');

It seems somewhat obvious to remind you, at this point, but if no expression is passed in (as either a regex literal or a string) then no filtering will occur, the plugin will return the same elements it received, to illustrate:

$('body, body *').hasAttrMatching().css('color', 'red');

Which, as you can see in the linked demo, colours all elements matched by the original selector.

References:

  • Plain JavaScript:
    • JavaScript regular expressions.
    • Object.hasOwnProperty().
    • test().
    • typeof operator.
  • jQuery:
    • css().
    • filter().
like image 178
David Thomas Avatar answered Jun 18 '26 19:06

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!