简体   繁体   中英

How to get the td that contains tr with a button that has a specific attribute?

I'm trying to get all the tds in a table that contain a tr with a button to which I have specified an attribute ("boolean") with a true or false value. I need to get each td that have that attribute with value true but I can't figure out how to get it using jquery.

The structure would be the following:

<table id="table">
    <thead>
    </thead>
    <tbody>
        <tr row-id="1">
            <td class="text-left">
                            <div />
            </td>
            <td class="text-left td-button">
                <button boolean="true">Button</button>
            </td>
        </tr>
        <tr row-id="2">
            <td class="text-left">
                <div />
                        </td>
            <td class="text-left td-button">
                <button boolean="false">Button</button>
            </td>
        </tr>
        <tr row-id="3">
            <td class="text-left">
                <div />
            </td>
            <td class="text-left td-button">
                <button boolean="true">Button</button>
            </td>
        </tr>
    </tbody>
</table>

I have tried to do something like this:

function colour() {
    $("#table tbody tr").each(function() {
        let colour = $(this).children("td")[1];     
    }
}

But I can't go from there to get those td since I have no experience with jquery

How could I get the td with row-id 1 and 3 with Jquery and then apply a style to those td? Thanks in advance

Use a has selector with attribute selector

 var trs = $('tr:has(button[boolean="true"])'); console.log(trs);
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <table id="table"> <thead> </thead> <tbody> <tr row-id="1"> <td class="text-left"> <div /> </td> <td class="text-left td-button"> <button boolean="true">Button</button> </td> </tr> <tr row-id="2"> <td class="text-left"> <div /> </td> <td class="text-left td-button"> <button boolean="false">Button</button> </td> </tr> <tr row-id="3"> <td class="text-left"> <div /> </td> <td class="text-left td-button"> <button boolean="true">Button</button> </td> </tr> </tbody> </table>

 $("#table tbody tr").each(function() { 
      //Filter to iterate those td's which contain Boolean true                                             
     if($(this).find('button').attr('boolean')=="true"){
      let colour = $(this).children("td")[1]; 
      colour.style.backgroundColor="red";
      console.log(colour); 
     } 
 })

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