zm455
zm455

Reputation: 499

JQuery selector: select td if sibling has .class

Hello I would like to select the first td of a row if one of that row has .foo class

<tr>
    <td>Holland</td>
    <td>Usa</td>
    <td>Japan</td>
    <td class="foo">France</td>
    <td>Spain</td>
</tr>

So in this code I would like to get Holland.

Note: later I will need to append a string "Welcome to" to the node. I.E: "Welcome to holland". Note2: I have multiple rows and multiple table element in my html code so it is not so easy to find the good selector I need

Upvotes: 0

Views: 1050

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115232

Use :has() and :first-child for that

$("tr:has(td.foo) td:first-child").css('color', 'red');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
  <tr>
    <td>Holland</td>
    <td>Usa</td>
    <td>Japan</td>
    <td class="foo">France</td>
    <td>Spain</td>
  </tr>
  <tr>
    <td>Holland</td>
    <td>Usa</td>
    <td>Japan</td>
    <td>France</td>
    <td>Spain</td>
  </tr>
  <tr>
    <td>Holland</td>
    <td>Usa</td>
    <td>Japan</td>
    <td class="foo">France</td>
    <td>Spain</td>
  </tr>
</table>

Upvotes: 4

Related Questions