Pete B
Pete B

Reputation: 15

Jquery - putting variables in :contains()

I am trying to write a simple piece of Jquery in which the script will check whether a table cell contains a range of numbers.

I'm unsure how to do this, because if you were to do something like this:

var num_range = ">1";
$("td:contains(" + num_range + ")").css('background-color', '#000');

...the script only detects if the td contains the exact text ">1", rather than what I'm after, it detecting whether any tds contain any numbers greater than 1. (Any then styling the background)

Thanks for any help, I'm a Javascript/Jquery novice!

Upvotes: 0

Views: 659

Answers (2)

cletus
cletus

Reputation: 625017

There's no native jQuery selector for this. You could write one if you want or just use:

$("td").each(function() {
  if (parseInt($(this).text()) > 1) {
    $(this).css("background", "#000");
  }
});

If you want to create your own selector:

$.extend($.expr[":"], {
  expr: (function() {
    var op = {
      '=': function(n1, n2) { return n1 == n2; },
      '!=': function(n1, n2) { return n1 != n2; },
      '>': function(n1, n2) { return n1 > n2; },
      '>=': function(n1, n2) { return n1 >= n2; },
      '<': function(n1, n2) { return n1 < n2; },
      '<=': function(n1, n2) { return n1 <= n2; }
    };
    var ops = [];
    for (p in op) {
      ops.push(p);
    }
    var r = new RegExp("^\\s*(" + ops.join("|") + ")\\s*(-?\\d+(?:\\.\\d+)?)\\s*$");
    return function(elem, i, match) {
      var m = r.exec(match[3]);
      return m && op[m[1]](parseFloat($(elem).text()), parseFloat(m[2]));
    };
  })()
});

And then you can do:

$("td:expr(>5)").css("background", "yellow");

Upvotes: 4

SLaks
SLaks

Reputation: 887275

There is no built-in selector in jQuery that does this.

You can use .filter to manually fund the elements. (by calling .text in the filter)

Upvotes: 1

Related Questions