Skip to content
Advertisement

How can I find the length of the table rows which have opacity 1 with style attribute?

I’m trying to find the length of the table rows which have opacity 1 applied by style attribute. The style="opacity: 1;" is applied dynamically so there could be 1 tr or a thousand trs with that way of styling applied and they could applied randomly. Not just the last two as shown in the demo below.

Here’s an example of how the TRs look:

<table>
     <tbody>
         <tr style="opacity: 0; display: none;"></tr>
         <tr style="opacity: 0; display: none;"></tr>
         <tr style="opacity: 0; display: none;"></tr>
         <tr style="opacity: 0; display: none;"></tr>
         <tr style="opacity: 1; display: table-row;"></tr>
         <tr style="opacity: 1; display: table-row;"></tr>
     </tbody>
</table>

I have tried the code below but getting this error:

Uncaught Error: Syntax error, unrecognized expression: [object HTMLTableRowElement][style*="opacity:1"]

Here’s the code:

const trArr = [];

$( 'table tr' ).each( ( idx, item ) => {
     trArr.push( $( `${item}[style*="opacity:1"]` ) );
});

console.log( trArr.length ); 

// Expected Output: 2

What am I doing wrong here?

Advertisement

Answer

You try checking the opacity value:

const trArr = [];

$( 'table tr' ).each( ( idx, item ) => {
  var o = $(item).css('opacity');
  if(o == 1){
    trArr.push(item);
  }
});

console.log( trArr );
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
     <tbody>
         <tr style="opacity: 0; display: none;"></tr>
         <tr style="opacity: 0; display: none;"></tr>
         <tr style="opacity: 0; display: none;"></tr>
         <tr style="opacity: 0; display: none;"></tr>
         <tr style="opacity: 1; display: table-row;"></tr>
         <tr style="opacity: 1; display: table-row;"></tr>
     </tbody>
</table>
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement