classList.add querySelector

Hi all re my code here https://codepen.io/Juc1/pen/YzBexYr

This works to add a class to the first p element:

const myconst = document.querySelector('p'); 
myconst.classList.add("myclassname");

But if I want to add a class to all p elements this does not work and gives the error “myconst.classList is undefined”:

const myconst = document.querySelectorAll('p'); 
myconst.classList.add("myclassname");

Why does querySelectorAll not work and how instead can I say add a class to all p elements?

Thanks…

const myNodes = document.querySelectorAll('p');

myNodes.forEach(node => {
  node.classList.add('myclassname');
});

.myclassname{
  color:red;
}

querySelectorAll returns a NodeList and you have to access each element inside the collection. It is much like how you would work with a normal array.

Ok thank you @zaklina and @lasjorg :+1:

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.