24

Is there a possibility in jQuery to select by multiple possible attribute values without having to use a comma separated list of selectors.

So in stead of:

#list1 > option[value="1"], #list1 > option[value="2"], etc

Something like:

#list1 > option[value="1"|value="2"], etc
2
  • The closest would be jQuery('[attribute*="value"]'). Attribute contains value selector. Commented Mar 29, 2011 at 11:36
  • @JohnP: hmmm, I was really hoping for exact values, as per this question, and my somewhat ugly answer to it: stackoverflow.com/questions/5471777/… Commented Mar 29, 2011 at 11:38

3 Answers 3

40

Not that I know of. The cleanest way I can think of doing this is to first select using the common elements across all items, then just .find() or .filter() the OR values out.

Something like

$('#list1 > option[value]')
    .filter('[value="1"],[value="2"]')
    ;
Sign up to request clarification or add additional context in comments.

5 Comments

... or perhaps extend jQuery with your own chain wrapper function. :D
Ah yes, that's not so bad actually (referring to your answer, not the comment ;-)). Upvote from me. :)
Not saying the comment is bad BTW. But not that well versed in jQuery to even know what you're talking about exactly, let alone know how to hack it together. :)
@fireeyedboy ~ ah, don't worry about it. :D It'd make for some good reading though when you find the time, so this is basically the gist of it: me.lt/4xl6P . Of course, better documentation over on the jQuery site itself. :D
ah yes, I see what you mean now. I've seen that before in various plugins. I'm afraid hacking together proposed functionality of my question would be pretty tricky though. ;-) I don't think I could be bothered to do it, seeing your answer is pretty damn clean already as far as I'm concerned. One could probably win a few milliseconds with such an implementation. But I just don't care enough. :-P Thanks for the link though. Useful nonetheless!
2

You can make a custom jQuery function like this:

$.fn.filterAttrVals = function (attr, vals) {
    var filter = '[' + attr + '="' + vals.split(',').join('"],[' + attr + '="') + '"]';
    return this.filter(filter);
};

For your example you could use it in the following way:

$('#list1 > option').filterAttrVals('value','1,2');

Comments

0

You can do this

var valuesNeeded = [1,2,etc];

$('#list1 > option').filter(function( index ) {
    return valuesNeeded.indexOf($(this).attr('value')) != -1;
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.