wkm
wkm

Reputation: 1762

Easier way to write multiple "not equal" attribute selectors?

I currently have a selector that looks like this:

$("span[row!='2'][row!='5'][row!='1']");

Is there an easier way to write this? I tried this but it didn't work:

$("span[row!='1,2,5']");

Upvotes: 2

Views: 3312

Answers (2)

jfriend00
jfriend00

Reputation: 707546

If you have to do this a lot and there isn't a better way to solve this problem by attaching appropriate classes to the like groups of rows, then you could write a short jQuery plugin that you could pass an array of row numbers to like this:

$("span[row]").filterAttribute("row", ['1','2','5'], true)

And this is an implementation of that:

$.fn.filterAttribute = function(attr, values, reverse) {
    var remaining = [];
    this.each(function(index, el) {
        for (var i = 0; i < values.length; i++) {
            if (el.getAttribute(attr) == values[i]) {
                remaining.push(el);
                break;
            }
        }
    });
    if (reverse) {
        return(this.not(remaining));
    } else {
        return($(remaining));
    }
}

You can see it work here: http://jsfiddle.net/jfriend00/WwrSY/

Note, the normal operation of this plugin is to filter items from the jQuery object so that items that do not match are removed, returning a new jQuery object with the specified items as the only ones kept (like jQuery's .filter() works. The third parameter can reverse the filter so that the items specified will be the ones removed, not kept which is what the OP has asked for with their != syntax.

Due to the wonders of automatic type conversion, this can also be used like this with the values passed as numbers:

$(".aaa").filterAttribute("row", [1, 2, 3], true)

Upvotes: 2

JaredPar
JaredPar

Reputation: 754943

No there is no way to combine not equal selectors in this manner. The result would be interpretted as the string '1,2,3' and not individual values. You'll have to enumerate the cases.

You could though write a function to make this easier to write. For example

var makeNotEquals = function(name) {
  var clause = '';
  for (var i = 1; i < arguments.length; i++) {
    clause = clause + '[' + name + '!=\'' + arguments[i] + '\']';
  }
  return clause;
}

Usage

var selector = 'span' + makeNotEquals('row', 2, 1, 5);
$(selector) 

Upvotes: 2

Related Questions