Vanilla JS: Add class Baz to all <li> with class Foo if they contain a descendant <div> with class Bar

Would like a vanilla JS solution, ie no jquery etc.

I have several

  • on page with the class Foo.

    Some of these contain a with the class Bar (not as a direct child).

    I want to add the class Baz to any Foo

  • that contains a descendant with class Bar.

    Any assistance would be wonderful. Many thanks!

    This is what I have so far. I am sure the contains syntax is where I am getting this wrong.

    const addClassTo = document.querySelectorAll('li.foo').contains('div.bar');
    addClassTo.forEach((element) => {element.classList.add('baz');})
    

    ;

    >Solution :

    const addClassTo = Array.from(document.querySelectorAll('li.foo')).filter((ele) => ele.querySelector('div.bar'))
    addClassTo.forEach((element) => {element.classList.add('baz');})
    
  • Leave a Reply