简体   繁体   中英

how to give a certain td a class name with javascript?

In a foreach loop in php, a list of rows with its td is created. In 1 of these rows, the folder has the name tmp . Is it possible to give that td a class hidden so that the folder is not visible?

This is how the foreach produces my html:

<tr>
  <td>
     <a href="#">tmp</a>
  </td>
  <td>
     Jan 31 '19
  </td>
  <td>
     1.2 Kb
  </td>
  <td>
     .png
  </td>
  ///

So: the td in which the anchor with the name tmp should get the class name: hidden liek below:

<tr>
  <td class="hidden">
     <a href="#">tmp</a>
  </td>
  <td>
     Jan 31 '19
  </td>
  <td>
     1.2 Kb
  </td>
  <td>
    .png
  </td>
  ///

Why not just give it the class on the server?

If not then

 //$("td:has('a')").addClass("hidden"); // OR $("td:has('a:contains(tmp)')").hide() 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td> <a href="#">tmp</a> </td> <td> Jan 31 '19 </td> <td> 1.2 Kb </td> <td> .png </td> </tr> </table> 

I wonder why you are not doing it on server side as @mplungjan suggested, but if you want to do it on client side instead of server side;

 $(function() { $("#folders a:contains('tmp')").parents("td").addClass("hidden"); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="folders"> <tr> <td> <a href="#">tmp</a> </td> <td> Jan 31 '19 </td> <td> 1.2 Kb </td> <td> .png </td> </tr> </table> 

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