Find td with specific text, and operate on the td right after that one?
26,843
Solution 1
First, you want to use :contains:
jQuery( "td:contains(text)" );
Then, you can use .next and .append:
jQuery( "td:contains(text)" ).next().append("Hello");
Here's a working snippet to demonstrate usage:
jQuery(function($) {
$("td:contains(Text to Find)").next().append(" Hello");
});
table {
border-collapse: collapse;
}
td {
border: 1px solid #ccc;
padding: 2px 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<table>
<tbody>
<tr>
<td>Some Text</td>
<td>More Text</td>
<td>YMT</td>
</tr>
<tr>
<td>Text to Find</td>
<td>Modify:</td>
<td>Do nothing here</td>
</tr>
</tbody>
</table>
Solution 2
jQuery has :contains()
pseudo class :
$('td:contains("Section Heading 4")').next().text(function(_,t){
return t + ' Hello';
})
Be carefull, :contains
is case sensitive.
Author by
Ahmad
Updated on January 13, 2020Comments
-
Ahmad over 4 years
I'm not very familiar with jQuery selectors, so would like some help.
I have a table like this:
<table class="test"> <tr> <td>Section Heading 1</td><td>Section Text 1</td> </tr> <tr> <td>Section Heading 2</td><td>Section Text 2</td> </tr> <tr> <td>Section Heading 3</td><td>Section Text 3</td> </tr> <tr> <td>Section Heading 4</td><td>Section Text 4</td> </tr> <tr> <td>Section Heading 5</td><td>Section Text 5</td> </tr> </table>
What I need to do is find the
td
containing a specific text, and the operate on the text in thetd
on its right.For example, say I want to find the
td
containing the textSection Heading 4
, and the concatenate the text contained in thetd
to it's right, with the texthello
, so thatSection Text 4
becomesSection Text 4 hello
..Which jQuery selector(s) can be used for this purpose ?
-
random_user_name over 10 yearsNice function. I'd upvote, but the OP specifically asked about a jQuery selector, which you are not using...
-
random_user_name over 10 years@Ahmad - It works. You just have to put the desired text in it, such as:
jQuery("td:contains(Heading 1)")....