2

I have a function that scans a table for a variable (keyID) and selects the table cell that contains that variable. The variable is currently defined as:

selectedTD = table.find('td:contains("' + keyID + '")');

However if keyID = 10, then selectTD will return a value if a table cell contains 10, 100, 1010 etc.

How can I make the variable selectTD only select the table cell when keyID is an exact match, rather than contains?

rlsaj
  • 735
  • 1
  • 12
  • 37

3 Answers3

1

Use filter() to pass each item in the collection through a function that returns true if the item should be included:

selectedTD = table
                .find('td')
                .filter(
                    function() { 
                        return this.innerText === keyID 
                    });

ETA: If you can control the HTML generated I suggest you add the keyID as a data- attribute such as <td data-keyid="keyhere">. Then you can simply use $('td[data-keyid=' + keyID + ']')

Malk
  • 11,855
  • 4
  • 33
  • 32
1

There's no single, native jQuery selector that will let you do that, but good answers here. Alternatively, this jQuery extension looks promising.

Community
  • 1
  • 1
Madbreaks
  • 19,094
  • 7
  • 58
  • 72
0

Try using .filter() like:

selectedTD = table.find('td').filter(function(){
    return $.trim(this.innerHTML) == keyID;
});
Ben Jackson
  • 11,722
  • 6
  • 32
  • 42