Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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>
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading