I try to select the td
element which contains "Text1" without giving this td
element an ID. So "Text1" should have a background color of red at the end. I tried it like this, but this does not work.
$("#test").parent().closest("td").css("background-color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <p> Text1 </p> </td> <td id="test"> <p> Text2 </p> </td> </tr> </table>
Use :contains
selector
$('td:contains("Text1")').css("background-color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <p> Text1 </p> </td> <td id="test"> <p> Text2 </p> </td> </tr> </table>
You can use prev()
method like following.
$("#test").prev('td').css("background-color", "red");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <table> <tr> <td> <p> Text1 </p> </td> <td id="test"> <p> Text2 </p> </td> </tr> </table>
Edit : Here's a JS solution using the ID :
$("#test").parent().find("td:first-child").css("background-color", "red");
Try like this:
$("#test").parent().children("td:nth-child(1)").css("background-color", "red");
working codepen: http://codepen.io/anon/pen/wGMZYG
How to select first child of parent by using ID of a child element?
I try to select the td element which contains "Text1"
Solution for the both the queries.
Code snippets:
$("#test").parent().children('td:first:contains("Text1")').css("background-color", "red");
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.