Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery attribute selector: [x=y] or [x=z]

I have the following jQuery selector:

$("a[href^='http://'],a[href^='https://']");

Is it possible to change this so that I don't need to specify a[href^= twice?

For example, something like:

$("a[href^='http://'||'https://']");

EDIT: My example of http and https should not be taken literally. I could be looking for values starting with y and z instead.

like image 613
Curtis Avatar asked Aug 09 '12 16:08

Curtis


1 Answers

Quite simple if you're willing to use a second function call:

$('a').filter('[href^="http://"],[href^="https://"]');

Or with tokens:

var startsWith = ['http://', 'https://'];
$('a').filter(function () {
    var i;
    for (i = 0; i < startsWith.length; i++) {
        if ($(this).is('[href^="' + startsWith[i] + '"]')) {
            return true;
        }
    }
    return false;
});

Or with a custom expression:

$.expr[':']​​​​​​.hrefStartsWith = function (ele, i, info) {
    var tokens;
    tokens = info[3].split(',');
    for (i = 0; i < tokens.length; i++) {
        if ($(ele).is('[href^="' + tokens[i] + '"]')) {
            return true;
        }
    }
    return false;
};

Which would be used as:

$('a:hrefStartsWith(http://,https://)')
like image 143
zzzzBov Avatar answered Sep 21 '22 00:09

zzzzBov