4

This function should search the document for any element with a 'data-info' attribute with a value of 'graphicDesign' then toggle the class 'hideMe' on those elements.

It returns the correct amount of elements in the console, but breaks on the classList toggle.

I've tried alternatives such as finding elements by class name then toggling, but this doesn't work either.

function toggleGraphicDesign() {
    let graphicDesignElements = document.querySelectorAll('[data-info="graphicDesign"]');
    console.log(graphicDesignElements.length);

    graphicDesignElements.classList.toggle('hideMe');

}

1 Answer 1

6

querySelectorAll() return a NodeList not a single element.According to MDN

The Document method querySelectorAll() returns a static (not live) NodeList representing a list of the document's elements that match the specified group of selectors.

You need to loop through all the elements using forEach() and toggle class of each element.

function toggleGraphicDesign() {
    let graphicDesignElements = document.querySelectorAll('[data-info="graphicDesign"]');
    console.log(graphicDesignElements.length);
    graphicDesignElements.forEach(x => x.classList.toggle('hideMe')) 
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.