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

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.

    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

    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');})
    
  • 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