0

I'm sure I've make a mistake but I can't figure it out...

Why I cannot select the elements with class name test by `querySelectorAll?

I'm getting an error: cannot read properties of undefined, but the elements are definitely defined because when I type content in the console, it shows the nodeList...

const content = document.querySelectorAll('.test');

content.classList.add('hide-content');
.Content {
  width: 180px;
  height: 90px;
  background-color: green;
}

.hide-content {
  display: none
}
<div class="Content"></div>
<div class="Content test"></div>
<div class="Content test"></div>
  • `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.` Use the document.querySelectorAll('.test')[0] or document.querySelector('.test') – James Mar 15 '22 at 19:59
  • _“but the elements are definitely defined”_ — That’s not what the error message is about. – Sebastian Simon Mar 15 '22 at 20:08

2 Answers2

0

You are selecting the elements, the problem is that content is not a single element, but a NodeList. In order to manipulate each element, you'll need to iterate over it with .forEach and apply the change to each element.

const content = document.querySelectorAll('.test');

content.forEach((el) => {
  el.classList.add('hide-content');
})
.Content {
  width: 180px;
  height: 90px;
  background-color: green;
}

.hide-content {
  display: none
}
<div class="Content"></div>
<div class="Content test"></div>
<div class="Content test"></div>

More notes on reading errors:

The error message is very useful so be sure to read it carefully in the future. The error says:

Cannot read properties of undefined (reading 'add')

Notice it says "reading 'add'". This means the error isn't saying that your query result is undefined, but that classList is undefined. Understanding this difference may lead you to investigate what content actually is and get you closer to solving your problem.

Brian Thompson
  • 13,263
  • 4
  • 23
  • 43
  • It's not an array. It's an "array-like" collection of elements. You can't, for example, use `map` on it until you convert it to an actual array. – Andy Mar 15 '22 at 20:04
0

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.

It is like the document.getElementsByClassName which return you a nodelist and you have to specify the index or you could use document.querySelector

const content = document.querySelectorAll('.test');

content[0].classList.add('hide-content');
.Content {
  width: 180px;
  height: 90px;
  background-color: green;
}

.hide-content {
  display: none
}
<div class="Content"></div>
<div class="Content test"></div>
<div class="Content test"></div>

If there are several of them, use an array like forEach or for loop instead

James
  • 2,732
  • 2
  • 5
  • 28