Skip to content
Advertisement

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

    <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?

Advertisement

Answer

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>
Advertisement