Home > Blockchain >  How to use querySelectorAll only for elements that have a specific child element?
How to use querySelectorAll only for elements that have a specific child element?

Time:11-22

<table>
  <tr>
    <th>Column name</th>
    <th>Column name</th>
  </tr>
  <tr>
    <td>Column value</td>
    <td>Column value</td>
  <tr>
</table>
<table>
  <tr>
    <th>Column name</th>
    <th>Column name</th>
  </tr>
  <tr>
    <td>Column value</td>
    <td>Column value</td>
  <tr>
</table>

I'd like to process all tr that contain a td, but can only find contain queries for attributes and content; not elements. Is the latter possible with a single query?

CodePudding user response:

Not directly, but you can use filter to get the appropriate rows

const rowsWithTd = [...document.querySelectorAll("table tr")].filter( x => x.querySelector("td"))
console.log(rowsWithTd.map(x => x.outerHTML))
<table>
  <tr>
    <th>Column name</th>
  </tr>
  <tr>
    <td>Column value</td>
  <tr>
</table>
<table>
  <tr>
    <th>Column name</th>
  </tr>
  <tr>
    <td>Column value</td>
  <tr>
</table>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related