Home > Software engineering >  How to select closest attribute with custom attribute name in jQuery
How to select closest attribute with custom attribute name in jQuery

Time:09-28

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

CodePudding user response:

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>

CodePudding user response:

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");
});
  • Related