I am trying to turn all of the items below into green when clicking the button, however only the first appearance of the class comes to effect, the rest won't respond. Any solution to this?
let testArr = document.getElementsByClassName('testclass');
testArr = Object.entries(testArr);
document.querySelector('#btn1').onclick = function () {
testArr.forEach(switchColor);
function switchColor() {
testArr = document.querySelector(".testclass");
testArr.style.color = "green";
}
}
<h1>For each practice</h1>
<ul>
<li>
<p >1</p>
</li>
<li>
<p >2</p>
</li>
<li>
<p >3</p>
</li>
<li>
<p >4</p>
</li>
</ul>
<button id="btn1">Click me</button>
CodePudding user response:
As specified in DOM4, elementsbyclassname returns an HTMLCollection not any array so forEach won't be useful. yeah but you can use it like this
Array.from(document.getElementsByClassName("testclass")).forEach(switchColor);
let testArr = document.querySelectorAll('.testclass');
document.querySelector('#btn1').onclick = function () {
testArr.forEach(switchColor);
function switchColor(item) {
item.style.color = "green";
}
}
<h1>For each practice</h1>
<ul>
<li>
<p >1</p>
</li>
<li>
<p >2</p>
</li>
<li>
<p >3</p>
</li>
<li>
<p >4</p>
</li>
</ul>
<button id="btn1">Click me</button>
CodePudding user response:
The return value is an HTMLCollection
, which, as you've seen, is an array-like object and not an array object so it doesn't have the array prototype functions including forEach
.
A fast and easy way to convert an HTMLCollection to an array of elements is using the spread ...
operator in an array literal []
: [...collection]
.
let elements = document.getElementsByClassName('testclass'); // HTMLCollection
let elementArray = [...elements] // Array
document.querySelector('#btn1').onclick = function () {
elementArray.forEach((element) => element.style.color = "green")
}
<h1>For each practice</h1>
<ul>
<li>
<p >1</p>
</li>
<li>
<p >2</p>
</li>
<li>
<p >3</p>
</li>
<li>
<p >4</p>
</li>
</ul>
<button id="btn1">Click me</button>
I also rewrote the forEach since it now loops through the elements, we don't need to reselect them.