tags:

views:

59

answers:

4

Hi there,

I have a couple divs like so:

<div>1</div>
<div>2</div

all the way through to

<div>11</div>
<div>12</div>

And so on.

What I'm wanting is a jquery select that picks one of these, like so:

$('.ticketNumber:contains("1")').addClass('something');

The problem with this of course, is its going to select any of the divs that contain the number 1 and not just the one that only contains 1.

So how does one go about telling jquery to do an exact select rather than a wildcard type?

+1  A: 

While filter is an easy option, you could do a little preprocessed to select more quickly.
This code created an array of tickets, for easy access. This is good if they don't change often, and have small numbers (otherwise the array would be too big, but you can easily switch to an associative array):

var tickets = [];

$(function(){
  $('div').each(function(){
    var div = $(this);
    var n = parseInt(div.text(), 10);
    tickets[n] = div;
  }); //div.each

  tickets[12].css('color', 'red');
}); //doc.ready

The next option is less popular, but works well. jQuery does similar things internally, by the way. Here, we use attr to add a custom attribute and select by it (if it bothers you, you can add a class like ticket12, or use a standard attribute). This is easier to maintain than an array if you make a lot of changes to your page:

$(function(){ 
  $('div').each(function(){ 
    var div = $(this); 
    var n = div.text(); 
    div.attr('ticket', n); 
  }); //div.each 

  $('[ticket=3]').css('color', 'blue'); 
}); //doc.ready

See both examples in action here: http://jsbin.com/etapu3

Kobi
+2  A: 

you can extend the selector

$.extend($.expr[':'],{
  containsNumber: function(a,i,m) {

    var text = $(a).text();

    return parseInt(text) == parseInt(m[3]);
  }
});

then you can use your extended selector

$('.ticketNumber:containsNumber(1)').addClass('something');
Anwar Chandra
thats interesting. never though to do that
cosmicbdog
not a very common scenario, but this : `<span>025</span>` would be matched by this: `$("span:containsNumber(31)")`. Always add the second parameter to `parseInt`! eg: `parseInt(m[3], 10)`
nickf
@q8-coder .very well done. Did not know it was possible to extend a search expression.
Neeraj Singh
A: 

Thanks everyone.

What i wound up using was :eq in the end

cosmicbdog
I can't believe it... I had a comment suggesting eq, but though it was too simple and you probably knew that... Oh, well. I guess it will benefit someone...
Kobi
thanks Kobi. I don't know why i didn't think to use eq :| Your solution will come in very handy though in another situation when the selection criteria isn't so linear as a bunch of divs with 1,2,3 etc.
cosmicbdog