Home > Mobile >  selector to extract value from table cell
selector to extract value from table cell

Time:05-24

I wanted to get the time value 15:43:42 from the table cell <td style="">15:43:42</td> . however the console test seems not exactly correct.

Which selector should I used and how to extract the value?

HTML:

<div  style="outline: green dotted 2px !important;">
   <table style="">
      <thead  style="">
         <tr style="">
            <th >Date</th>
            <th >Time</th>
            <th >Model</th>
         </tr>
      </thead>
      <tbody  style="">
         <tr data-row-key="852db0ee-bbaa-4aa2-a1ee-60836c6b5980" >
            <td  style=""><label ><span ><input type="checkbox"  value=""><span ></span></span></label></td>
            <td  style="">
            </td>
            <td  style="">23/05/2022</td>
            <td  style="">15:43:42</td>
            <td >16000samplerate-60train-40test-v1-16k</td>
         </tr>
      </tbody>
   </table>
</div>

The console result of document.querySelectorAll('table tr td:nth-child(4)');

console result

CodePudding user response:

firstly querySelectorAll selects all matching elements and returns always a nodeList and not a single element. To select a single element use querySelector and then be very specific which element do you want select. In your example you can do it that way

const tdNode = document.querySelector('tbody > tr td:nth-child(4)');
const text = tdNode.innerText;

and of course it would be easier if you can set a class on the desired element.

CodePudding user response:

If you meant which JS selector you should use, then my answer is the following: Added a class to the desired td: cls.

var item = document.getElementsByClassName("cls");
for (let i = 0; i < item.length; i  ) {
    console.log(item[i].textContent);
}
<div  style="outline: green dotted 2px !important;">
   <table style="">
      <thead  style="">
         <tr style="">
            <th >Date</th>
            <th >Time</th>
            <th >Model</th>
         </tr>
      </thead>
      <tbody  style="">
         <tr data-row-key="852db0ee-bbaa-4aa2-a1ee-60836c6b5980" >
            <td  style=""><label ><span ><input type="checkbox"  value=""><span ></span></span></label></td>
            <td  style="">
            </td>
            <td  style="">23/05/2022</td>
            <td  style="">15:43:42</td>
            <td >16000samplerate-60train-40test-v1-16k</td>
         </tr>
      </tbody>
   </table>
</div>

  •  Tags:  
  • css
  • Related