简体   繁体   中英

How would I hide a table row if its <td> elements don't have one of two classes?

I need to hide all of the rows in a particular table whose td elements do not contain one of two classes.

If at least one of the td elements in a row contains one of these two classes, then don't hide it. Otherwise, hide the entire row.

class='class1'  
class='class2'  
id='mytable'

Any ideas?

Without an example it's difficult to know exactly what you are looking for, but perhaps something like this would work (air code):

$('#mytable tr').each(function() {
    var count = $('td.class1, td.class2', $(this)).length;
    if (!count) {
        $(this).hide();
    }
});

You can use this approach, perhaps it is not the shortest one, but hopefully clear to follow. Lookup find, hasClass, eq methods in jQuery to learn more.

var trs = $("table tr")

for( var i = 0; i < trs.length; i++) {
    var tds = $(trs.eq(i)).find("td");
  var trToKeep = true;
  for (var j = 0; j < tds.length; j++) {
    if (tds.eq(j).hasClass("x") || tds.eq(j).hasClass("y")){
        trToKeep = true;
      break;
    }
    else {
        trToKeep = false;
    }
  }
  if (trToKeep === false) {
  trs.eq(i).hide();
  } 
}

Working jsFiddle is here (classes you would look for are x or y):

https://jsfiddle.net/Turo/aj55q33w/


Update: Updated my answer as you wanted to hide the ones that do not have the classes, not the ones that do.

You can loop through the rows and check the class of each td . I have loop through and used array and flag to decide whether to show or hide. I also hide all at first then show them later with condition check.

var classNames = ['red', 'green'];
$(document).ready(function() {
  $('table tbody tr').each(function() {
    var show = false;
    $(this).hide();
    $('td', this).each(function() {
      var tdClass = $(this).attr('class');
      if ($.inArray(tdClass, classNames) != -1) {
        show = true;
      }
    });
    if (show) {
      $(this).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