Using a filter to apply class to many elements, Javascript

Hi everyone, i am experimenting with array method in JS and I’ve run in to an issue.

let wholePage =  !document.includes('popup');

const hideAll = () => {

What I want to do is find everything that does not have the class of ‘popup’ and when the button is clicked I want that all to have a hidden class applied to it. However nothing is happening when I click the button, so I must be wrong somewhere.

<button type="button" id="button1" onclick="hideAll()" class="popupbutton btn btn-info navbutton">Projects</button>

The button, just in case that was the issue.

Thank you all in advance for your help.

I would rather go with something like this:

function addClassTo(searchQuery, className) {
  // Select all elements with specific query, '.class' for classes, '#id' for ids, '[attr="value]' for attributes
  const elements = document.querySelectorAll(searchQuery);
  // Add class for each of the element
  elements.forEach(element => element.classList.addClass(className);

In addition to (EDIT: the post above - the forum automatically removed my quote), you can make use of the :not() pseudo-class in your searchQuery.

let searchQuery = ':not(.popup)';
let className = 'hidden';
addClassTo(searchQuery, className)

However, that’s a massively broad selector if your page has a decent number of elements, and it would likely be a good idea to find something more specific.

1 Like

I think I understand your example, however I have just a few questions if you don’t mind.
What should I put for search query? I want to everything that is NOT the popup class, I tried putting ‘!.popup’ but it my syntax was wrong.

@Imstupidpleasehelp User @partylich already showed you how to do that.

You’re right they did. So I put their answers together and got this.

function hideAll(searchQuery, className) {
let searchQuery = ':not(.popup)';
let className = 'hidden';
hideAll(searchQuery, className)

I get the error that searchQuery has already been declared.
I think I have burnt myself out. I will take another look at it in a few hours.

searchQuery has already been defined as the parameter.

There is no point in having a parameter for searchQuery if you are not actually going to pass a value into it though.

Also, you have called hideAll within the hideAll function. This will create an infinite recursive call that will error out.

You have not really combined the two responses at all. You need to make sure you understand how the solutions given by @partylich and @snigo actually work. See if you can explain why their solutions work.

Thanks everyone here for your answers. Sorry for taking up your time. I am feeling under the weather today and I should have just taken a day off when I encountered this problem. I will have a good night’s rest then solve it myself.
Again, thanks everyone.