'JavaScript why cannot select the elements [duplicate]
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>
Solution 1:[1]
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
Solution 2:[2]
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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | James |
| Solution 2 |
