Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery find elements that match criteria

Tags:

Got a tricky one where I want to add a class to all the parent <tr>'s of <td>'s which have either a <span> or a <div> element within them. So I have a table with markup as 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 the <td>'s that have either a <span> or <div> to have a class added to them by jQuery...

I can't seem to work out how to loop through all the <td>'s to check their descendant and then add the class to those that have either a <span> or <div> inside... Is this possible?

Thanks for any light you can shed on it! It's driving me mad!

like image 307
dubbs Avatar asked Apr 20 '16 21:04

dubbs


1 Answers

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

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

Check the below snippet:

$('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>
like image 176
The Process Avatar answered Sep 28 '22 02:09

The Process