简体   繁体   中英

jQuery selector td with specific text

I have a jquery selector which looks like this:

$("#MasterListDVWP tr td:contains('" + currentSchool + "')").siblings("td:contains('Yes')").siblings("td:contains('CD'),td:contains('Other1')").each(function() {
// do something
});

Could someone help me to convert the selector so that it returns the object that matches the exact text rather than just contains? I know this isn't valid but something like this..siblings("td:equals('CD')")...

Your help will be greatly appreciated.

your best bet is probably the .filter() function. Pass it a function that tests the text of the elements you're checking

$('#MasterListDVWP tr td').filter(function(){
  return $(this).text() === currentSchool;
}).siblings('td').filter(function(){
  return $(this).text() === 'CD' || $(this).text() === 'Other1';
}).each(function(){
  // do something
});

There is no jQuery selector like that, but you could create one:

jQuery.extend(jQuery.expr[':'], {
    containsExactly: function (obj, index, meta, stack) {
        if ($(obj).text() === meta[3]) {
            return true;
        }
        return false;
    }
});

If you do that, then you can now do:

$("#MasterListDVWP tr td:td:containsExactly('" + currentSchool + "')").siblings("td:containsExactly('Yes')").siblings("td:td:containsExactly('CD'),td:td:containsExactly('Other1')").each(function() {
// do something
});

Try it out!

It is not possible with bare selectors.

Maybe you can use .filter() like:

 $(...selectors...).filter(
     function (index) { return $(this).text() == "textToMatch"; }
);

For multiple filterings on the same element:

 $(...selectors...).filter(
     function (index) { 
          return $(this).text() == "textToMatch" && $(this).text()=="anotherText"; 
     }
);

or just chain various .filter() declarations together.

Use || (or) instead of && to find TD's with a text or another.

Filtering rows TD's with a text

$("#table_id tr td").filter(
     function (index) { return $(this).text() == text_to_find; }
).parent().show()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM