How to select this specific td element and its text with Jquery

前端 未结 6 470
温柔的废话
温柔的废话 2020-12-19 18:39

I want to change the \"Yes! Pick me\" into \"Picked\" with Jquery in the following HTML structure, I used $(\'#myDiv>table>tr>td>table>tr\').eq(1).text(

相关标签:
6条回答
  • 2020-12-19 19:11

    The main problem is that you want .eq(0) not .eq(1) as .eq() is 0-based, and you are not selecting the td, only the tr.

    Other than that using > direct descendant selectors makes your selection not very robust at all.

    Try $('#myDiv table table td').eq(0).text('Picked');

    0 讨论(0)
  • 2020-12-19 19:25

    Your child selector query won't work because HTML5 requires the parser to insert <tbody> elements inside your <table> elements, since you've forgotten to put them in yourself. Perhaps you should consider validating your HTML?

    0 讨论(0)
  • 2020-12-19 19:26

    Try this:

    $("#myDiv table table td:first").text("Picked")
    
    0 讨论(0)
  • 2020-12-19 19:27
    $('#myDiv').find('table table td').eq(0).text(...);
    

    Start your selection at the #myDiv element ($('#myDiv')), then find all the TD element that are inside a table that is inside another table (.find('table table td')), then only alter the first one (.eq(0)).

    Documentation:

    • .find(): http://api.jquery.com/find
    • .eq(): http://api.jquery.com/eq
    0 讨论(0)
  • 2020-12-19 19:38

    You can try:

    $("td:contains('Yes! Pick me!')").text("Picked"); ​
    
    0 讨论(0)
  • 2020-12-19 19:38

    You can use the :contains(text) selector

    $('#myDiv td table td:contains(Yes! Pick me!)').text('Picked');
    

    Be careful with nested tables however because if you were to use just

    $('#myDiv td:contains(Yes! Pick me!)').text('Picked');
    

    You would get both the cell your after plus the cell it is nested within.

    0 讨论(0)
提交回复
热议问题