3

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.

Evgenij Reznik
  • 17,916
  • 39
  • 104
  • 181

3 Answers3

2

First issue is that your FIDDLE doesn't work because you've forgotten to include jQuery.

The second issue is your query. Spacing is important when defining selectors. In your query, you have td:nth-child(1)[id$=2]. Because there is no space between td:nth-child(1) and [id$=2], you're basically looking for a td with a particular id. What you want is to find the input element within the td. This would be more appropriate td:nth-child(1) [id$=2] - notice the space between. The space indicates that you want to search all decendants of the td. If you wanted to search only direct children, you could use the > to denote that like this td:nth-child(1) > [id$=2].

You can simplify your query as well for this particular scenario. If you want all inputs that have an ID that ends in 2, then you can use jquery :input pseudo-selector to target them like so:

$(":input[id$=2]").css("background-color", "red");

https://api.jquery.com/input-selector/

Description: Selects all input, textarea, select and button elements.

Joel
  • 2,227
  • 1
  • 17
  • 23
1

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.

Munawir
  • 3,346
  • 9
  • 33
  • 51
  • 2
    What is important to note here is the space between the `td:nth-child(1)` and `[id$=2]`. This is because the element with id ending in 2 is a descendant and separate from the `td` – Cave Johnson Jun 02 '16 at 17:21
-1

jQuery Selector: Id Ends With?

http://api.jquery.com/all-selector/

Just take a look at this links..

If you know the element type then: (eg: replace 'element' with 'div')

 $("element[id$='txtTitle']")

or

use asterisk '*' at the beginning

   $('*[id*=mytext]:...

like this

Community
  • 1
  • 1