user1170330 user1170330 - 6 months ago 10
jQuery Question

Select all elements in TD with certain ID

How can I select all elements in my

td
whose id ends with a
2
?

In my code, the
IDs
of the 2nd and 4th element end with a
2
, so those elements background color should turn red.

<table>
<tr>
<td>
<input type="text" id="abc|1">
</td>
</tr>
<tr>
<td>
<select id="def|2">
<option>123</option>
<option>456</option>
<option>789</option>
</select>
</td>
</tr>
<tr>
<td>
<input type="radio" id="ghi|1" />
</td>
</tr>
<tr>
<td>
<input type="text" id="jkl|2">
</td>
</tr>
</table>


This is my approach:

$("table td:nth-child(1)[id$=2]").css("background-color", "red");


FIDDLE.

Answer

Use this jQuery

$("table td:nth-child(1) [id$=2]").css("background-color", "red");

JSFiddle : https://jsfiddle.net/torjpv9t/3/

Note : You can simply use $("[id$=2]") as selector.