简体   繁体   中英

How to select closest attribute with custom attribute name in jQuery

Hi Please see my below html code.

<tr> .....</tr>

<tr>
        <td data-colname="ctv">hello</td>
        <td class="my_t">Yes</td>
        <td class="mybutton">Click here</td>
        </tr>

<tr> .....</tr>

I can select my_t value in my custom function using

$(".mybutton").on("click",function(){
     $(this).closest("tr").find(".my_t").css("color","red");
});

it is working fine.

But below code is not working . how I can select data-colname="ctv " **in?

$(".mybutton").on("click",function(){
        $(this).closest("tr").find("[data-colname='ctv']").css("color","green");
    });

Please help

EDIT Added a snippet with the above code

 $(".mybutton").on("click", function() { $(this).closest("tr").find(".my_t").css("color", "red"); }); $(".mybutton").on("click", function() { $(this).closest("tr").find("[data-colname='ctv']").css("color", "green"); });
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr> <td data-colname="ctv">hello</td> <td class="my_t">Yes</td> <td class="mybutton">Click here</td> </tr> </table>

Indeed, no selection works with the code you provided as it is not enclosed in a <table> element. Please try this:

 var res = $(".my_t").parent().find("[data-colname='ctv']"); console.log(res);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table> <tr>.....</tr> <tr> <td data-colname="ctv">hello</td> <td class="my_t">Yes</td> </tr> <tr>.....</tr> </table>

One of the solutions that should work with this HTML structure:

$(".mybutton").on("click",function(){
    $(this).parents("tr").find("td[data-colname='ctv']")[0].css("color","green");
});

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM