Ross
Ross

Reputation: 14435

jQuery Attribute Selector with "OR" operator possible?

Is it possible to re-write the following selector using an "OR" operator or similar?

$("a[href$='avi'], a[href$='mov'], a[href$='mp4'], a[href$='m4v']")

Ideally something like:

$("a[href$='avi|mov|mp4|m4v']") // incorrect

to get a few more miles out of my keyboard. I have a test fiddle.

Upvotes: 2

Views: 2500

Answers (3)

user920041
user920041

Reputation:

You can do this by extending jQuery with James Padolseys Regex Selector for jQuery. Pretty useful when you want to put regex into your selectors.

Run this code in Test fiddle

jQuery.expr[':'].regex = function(elem, index, match) {
    var matchParams = match[3].split(','),
        validLabels = /^(data|css):/,
        attr = {
            method: matchParams[0].match(validLabels) ?
                        matchParams[0].split(':')[0] : 'attr',
            property: matchParams.shift().replace(validLabels,'')
        },
        regexFlags = 'ig',
        regex = new RegExp(matchParams.join('').replace(/^\s+|\s+$/g,''), regexFlags);
    return regex.test(jQuery(elem)[attr.method](attr.property));
}

$("a[href$='avi'], a[href$='mov'], a[href$='mp4'], a[href$='m4v']")
    .addClass("select");


$('a:regex(href,avi|mov|mp4|m4v)').addClass("betterSelect"); 

Upvotes: 2

T.J. Crowder
T.J. Crowder

Reputation: 1075925

No, CSS doesn't have this (it would be in the attribute selectors area) nor does jQuery add it (see the "attribute ends with" docs).

You could, of course, give yourself a utility function to do it if you don't mind not being able to match the | character, something vaguely like this:

(function($) {
    $.attrEndsWith = attrEndsWith;
    function attrEndsWith(tag, attr, list) {
        return $(tag + "[" + attr + "$='" + list.split("|").join("'], " + tag + "[" + attr + "$='") + "']");
    }
})(jQuery);

and used so:

$.attrEndsWith("a", "href", "avi|mov|mp4|m4v");

This is untested, but you get the idea.

Upvotes: 3

spicavigo
spicavigo

Reputation: 4234

$("a").filter(function(){ return /(avi|mov|mp4|m4v)$/i.test($(this).attr('href')); }).addClass('betterSelect');

Not really the answer you were looking for, but maybe it will help.

Upvotes: 1

Related Questions