Home > Blockchain >  jQuery to change background on table row based on values of two cells within that row
jQuery to change background on table row based on values of two cells within that row

Time:03-09

I have a tampermonkey script that highlights table rows when specific columns contain specific text.

For example the code below successfully highlights rows were column 1 contains 'M' and rows where column 3 contains 'P'.

$("td:nth-of-type(1):contains('M')").parent().css("background-color","#ccccff");
$("td:nth-of-type(3):contains('P')").parent().css("background-color","#ccccff");

How can I use an AND operator or an IF statement to highlight a row only if column 1 contains 'P' AND column 3 contains 'M'?

CodePudding user response:

Grab all the <tr> elements and filter that down to the ones with the <td> elements matching your requirements.

Once you have that filtered collection, set the background colour.

const MATCH = [{
  col: 0,
  chr: "M"
}, {
  col: 2,
  chr: "P"
}]

$("tr").filter((_, tr) => {
  // get the <td> children
  const cells = $(tr).children("td")
  // Ensure each MATCH appears in each cell respectively
  return MATCH.every(({ col, chr }) => cells.eq(col).text().includes(chr))  
}).css("background-color", "#ccf")
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.slim.min.js"></script>
<table border="1">
  <tr>
    <td>No capital "m" here</td>
    <td>foo</td>
    <td>No capital "p" here</td>
  </tr>
  <tr>
    <td>Mo Money</td>
    <td>bar</td>
    <td>Mo Problems</td>
  </tr>
  <tr>
    <td>Pass the</td>
    <td>baz</td>
    <td>Mayo please</td>
  </tr>
</table>

CodePudding user response:

Is this what you are trying to achieve?

if ($("td:nth-of-type(1)").text() == "M" && $("td:nth-of-type(2)").text() == "P") {
    $("td:nth-of-type(1)").parent().css("background-color", "#ccccff");
    $("td:nth-of-type(2)").parent().css("background-color", "#ccccff");
}
  • Related