Edward
Edward

Reputation: 4631

How to select an element by it's value in jQuery?

I have the following HTML-source

<tr>
  <td>Peter Pan</td>
  <td>Nervland</td>
  <td>
    <a href="edit/id-for-peterP">edit</a>
    <a href="delete/id-for-peterP">delete</a>
  </a></td>
</tr>
<tr>
  <td>Wendy</td>
  <td>Nervland</td>
  <td>
    <a href="edit/id-for-wendy">edit</a>
    <a href="delete/id-for-wendy">delete</a>
  </a></td>
</tr>

The task is to

choose the edit-link in the row that also contains a cell which contains "Peter Pan"

How can I (efficiently) solve this problem?

Upvotes: 0

Views: 22

Answers (3)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93611

If you do not care about other text in the field use :has and :contains,

var anchor = $('tr:has(td:contains("Peter Pan")) a[href^=edit]');

but if you want the entire text to match, use filter() with a boolean function like this:

var anchor = $('td').filter(function(){
    return $(this).text() == "Peter Pan";
}).closest('tr').find('a[href^=edit]');

it finds all TDs, then filters based on exact text matching, then finds the nearest ancestor TR and the link within that.

Upvotes: 0

kapantzak
kapantzak

Reputation: 11750

Select the row that contains the string Peter Pan and then find the link with href attribute starting with edit and make it red:

$('tr:contains("Peter Pan") a[href^=edit]').addClass('red');
.red { color:red }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<table>
<tr>
  <td>Peter Pan</td>
  <td>Nervland</td>
  <td>
    <a href="edit/id-for-peterP">edit</a>
    <a href="delete/id-for-peterP">delete</a>
  </td>
</tr>
<tr>
  <td>Wendy</td>
  <td>Nervland</td>
  <td>
    <a href="edit/id-for-wendy">edit</a>
    <a href="delete/id-for-wendy">delete</a>
  </td>
</tr>
</table>

Upvotes: 1

Alvin Magalona
Alvin Magalona

Reputation: 771

Use this code:

$( "td:contains('Peter Pan')");

Upvotes: 0

Related Questions