Reputation: 8394
For the given (incomplete) HTML table:
<tr>
...
</tr>
<tr>
<td><input type="radio"></td>
<td>Red Hot Chili Peppers</td>
<td></td>
</tr>
<tr>
<td><input type="radio"></td>
<td>Britney Spears</td>
<td></td>
</tr>
<tr>
...
</tr>
I use xpath selector //td[contains(., 'Red Hot Chili Peppers')]//preceding-sibling::td//input
to click a radio button.
The problem is that xpath is sometimes flaky on the page I'm testing. I wish to switch to jQuery.
How can I do this in jQuery?
Upvotes: 2
Views: 1126
Reputation: 272096
preceding-sibling
is supposed to match all preceding siblings, the most appropriate jQuery equivalent is prevAll
:
$("td:contains('Red Hot Chili Peppers')")
.prevAll("td")
.find("input")
Upvotes: 1
Reputation: 1546
Yes you can do that check this https://api.jquery.com/contains-selector/
for your code use
$('td:contains("Red Hot Chili Peppers")').prev('td').find('input');
I'ld suggest to use jQuery because I has many libraries build on top of it. You will easily find what you need.
Upvotes: 1
Reputation: 337560
The jQuery equivalent of that would use :contains
, prev()
and find()
, like this:
$('td:contains("Red Hot Chili Peppers")').prev('td').find('input')
$('td:contains("Red Hot Chili Peppers")').prev('td').find('input').prop('checked', true);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="radio"></td>
<td>Red Hot Chili Peppers</td>
<td></td>
</tr>
<tr>
<td><input type="radio"></td>
<td>Britney Spears</td>
<td></td>
</tr>
</table>
Upvotes: 3