skip to Main Content

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>

3

Answers


  1. 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>
    Login or Signup to reply.
  2. document.querySelectorAll('i:not(:has(font))');
    

    It should work.

    Login or Signup to reply.
  3. Because you’re spreading the NodeList that querySelectorAll() returns into an array with [...], we can just use array standard methods to remove DOM nodes from it:

    const elements = [...document.querySelectorAll("i")]
      .filter((el) => !el.querySelector("font"));
      
    console.log(elements);
    <i><font color="008000">Here goes some text</font></i>
    <br>
    <i>Select me!</i>
    <i>And <b>me too</b>!</i>
    <i>However, <span><font>I am doubly nested, don't select me</font></span></i>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search