Search code examples
jqueryindexingtableheader

hide elements according to index position using jquery


I have a dynamic table with many columns and rows. In some cells there is specific value "N/A". I want to hide cells containing "N/A" along with its table header too How is it possible using jquery

See Image

I tried this code and it works partially. Table cells were hidden perfectly but only first table header "material" is hidden.

jQuery(document).ready(function() {
  var findna = jQuery('tr').find('td:contains(N/A)').index();
  jQuery('tr').find('td:contains(N/A)').css('display', 'none');
  jQuery('table tr:first-child')
    .find("th:eq(" + findna + ")").css('display', 'none');

  console.log(findna)
});

Solution

  • You need to update your code to get all 3 indexes and then hide

    jQuery(document).ready(function() {
      jQuery('tr').find('td:contains(N/A)').each(function() {
        $(this).css('display', 'none');
      });
      jQuery('tr:nth-child(2)').find('td:contains(N/A)').each(function() {
        jQuery('table tr:first-child').find("th:eq(" + $(this).index() + ")").css('display', 'none');
      });
    });
    

    jQuery(document).ready(function() {
      jQuery('tr').find('td:contains(N/A)').each(function() {
        $(this).css('display', 'none');
      });
      jQuery('tr:nth-child(2)').find('td:contains(N/A)').each(function() {
        jQuery('table tr:first-child').find("th:eq(" + $(this).index() + ")").css('display', 'none');
      });
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <table>
      <tr>
        <th>Type</th>
        <th>Material</th>
        <th>Core</th>
        <th>Wire</th>
        <th>Vendor rate</th>
    
      </tr>
      <tr>
        <td>switch</td>
        <td>N/A</td>
        <td>N/A</td>
        <td>N/A</td>
        <td>30</td>
      </tr>
       <tr>
        <td>switch</td>
        <td>N/A</td>
        <td>N/A</td>
        <td>N/A</td>
        <td>50</td>
      </tr>
    </table>