Search code examples
javascripthtmlcssqueryselector

How to select only tags which does not have a specific tag inside of it


I want to be able to use querySelectorAll to query all i elements which does not have a font tag inside of it. I have tried the following selector, but it is not working:

  document.querySelectorAll('i > *:not(font)')
<i>
   <font color="008000">Here goes some text</font>
</i>
<br />
<i>Here goes another text</i>


Solution

  • The code in question doesn't select all i elements which do not contain a font element like you intend. It actually selects all children of i that are not font elements.

    console.log([...document.querySelectorAll('i>*:not(font)')])
    <i>
      <font color="008000">Here goes some text</font>
    </i>
    <br />
    <i>Here goes another text</i>

    For the behaviour you want, you'll need to use the new :has() selector in CSS which is available in all major browsers (except behind a flag in firefox):

    console.log([...document.querySelectorAll('i:not(:has(> font))')])
    <i>
      <font color="008000">Here goes some text</font>
    </i>
    <br />
    <i>Here goes another text</i>