Dexygen
Dexygen

Reputation: 12561

How to find table rows with no cells with a particular css class

In trying to help the asker of this question I performed a google search essentially equivalent to the title of this question and found nothing on point, for instance instead finding the following question for finding table rows that do contain cells with a particular class.

Despite answering the first question cited above, I'm creating this somewhat more narrow self-answered Q&A to

  1. Hopefully get this indexed by google for next time somebody searches for this, something not really possible with the first cited question above as it is actually a two part question (and within seconds, this is now the top result from Google), and
  2. To provide jQuery and non-jQuery answers to the question, the OP to the first cited question apparently not using jQuery

So, assuming the following HTML table is the only table on the page, how does one find the table rows without any cells with the class foo, using jQuery, or without jQuery?

<table border="1">
  <tr><td class='foo'>foo</td><td></td><td></td></tr>
  <tr><td></td><td>bar</td><td></td></tr>
  <tr><td></td><td></td><td>baz</td></tr>
  <tr><td class="foo">foo</td><td>bar</td><td>baz</td></tr>
</table> 

Upvotes: 1

Views: 212

Answers (1)

Dexygen
Dexygen

Reputation: 12561

To find table rows with cells that do have a particular CSS class, essentially all you have to do is craft a straightforward selector, e.g. $('tr:has(td.specialclass)') from an answer to the second question cited in the above question itself. To find the rows with no cells that contain a particular class, you can go a step further and use filter.

Using jQuery:

let $nonFooRows = $('tr').filter((i, tr) => {
    return !$(tr).has('td.foo').length;
});

Without jQuery:

let nonFooRows = [].filter.call(document.getElementsByTagName('tr'), (row) => {
    return !row.querySelector('td.foo');
});

I've created a demo of each of the above where the rows returned by the above get highlighted by clicking a button, here: https://repl.it/@dexygen/FindRowsWithNoCellsHavingClassFoo

Upvotes: 2

Related Questions