Home > Software design >  How to get the td that contains tr with a button that has a specific attribute?
How to get the td that contains tr with a button that has a specific attribute?

Time:01-12

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 >
                            <div />
            </td>
            <td >
                <button boolean="true">Button</button>
            </td>
        </tr>
        <tr row-id="2">
            <td >
                <div />
                        </td>
            <td >
                <button boolean="false">Button</button>
            </td>
        </tr>
        <tr row-id="3">
            <td >
                <div />
            </td>
            <td >
                <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

CodePudding user response:

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 >
                            <div />
            </td>
            <td >
                <button boolean="true">Button</button>
            </td>
        </tr>
        <tr row-id="2">
            <td >
                <div />
                        </td>
            <td >
                <button boolean="false">Button</button>
            </td>
        </tr>
        <tr row-id="3">
            <td >
                <div />
            </td>
            <td >
                <button boolean="true">Button</button>
            </td>
        </tr>
    </tbody>
</table>

CodePudding user response:

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