JQuery find items matching your criteria

It will be a difficult situation when I want to add a class to all the parent <tr> of <td> that have a <span> or <div> element in them. Therefore, I have a table with markup, as shown below:

 <table> <tr> <td> </td> <td> </td> <td> <div> </div> </td> <td> </td> </tr> <tr> <td> <span></span> </td> <td> </td> <td> <div> </div> </td> <td> </td> </tr> </table> 

So, I want <td> have either <span> or <div> to add a class to them using jQuery ...

I cannot figure out how to skip all the <td> tags to check their descendants, and then add a class to those that have either <span> or <div> inside ... Is this possible?

Thanks for any light you can shed on it! It drives me crazy!

+5
source share
1 answer

You can check with . has () if tr has a div or span as a child:

 $('table tr').has('div,span').addClass('someClass'); 

Check the snippet below:

 $('table tr').has('div,span').addClass('someClass'); 
 .someClass { background-color: red; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td>td 1</td> <td>td 2</td> <td> <div>div</div> </td> <td>td 3</td> </tr> <tr> <td>td 1</td> <td>td 2</td> <td>td 3</td> <td>td 4</td> </tr> <tr> <td><span>span</span> </td> <td>td 1</td> <td> <div>div</div> </td> <td>td 2</td> </tr> <tr> <td>td 1</td> <td>td 2</td> <td>td 3</td> <td>td 4</td> </tr> </table> 
+4
source

Source: https://habr.com/ru/post/1247554/


All Articles