Search code examples
javascriptwebdriver-io

Query to Search for DOM a Specific DOM element


In the DOM below, how can I search for the element that has "Subtotal" as innerText, and get the next/sibling element to get the actual value? In the Chrome console, I was able to do $$('tbody[class="MuiTableBody-root"]')[5].children[0].children[1]

I am specifically seeking the query to search for "Subtotal" and get the sibling.

<tbody class="MuiTableBody-root">
   <tr class="MuiTableRow-root">
      <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">Subtotal</td>
      <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">$0.00</td>
   </tr>
   <tr class="MuiTableRow-root">
      <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">Total</td>
      <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">$0.00</td>
   </tr>
   <tr class="MuiTableRow-root">
      <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">Total Price/Unit</td>
      <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">$0.00</td>
   </tr>
</tbody>

Solution

  • Would this work for you ?

    jQuery(document).ready(() => {
    
      var $tds = jQuery("td").each(function(){
        if(this.innerText.trim().toLowerCase() == "subtotal"){
          console.log(this.innerText);
          let $adjacent = $(this).next();
          let amount = $adjacent.text().trim();
          console.log(amount);
        }
        
      });
    
    
    })
    <html>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    
    
    </html>
    
    <body>
    
      <table class="MuiTableBody-root">
    
        <tr class="MuiTableRow-root">
          <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">Subtotal</td>
          <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">$0.00</td>
        </tr>
    
        <tr class="MuiTableRow-root">
          <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">Total</td>
          <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">$0.00</td>
        </tr>
        <tr class="MuiTableRow-root">
          <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">Total Price/Unit</td>
          <td class="MuiTableCell-root jss93 MuiTableCell-body MuiTableCell-alignRight">$0.00</td>
        </tr>
      </table>
      
    </body>