0

let colorOptArr = [
  document.getElementsByClassName("bx1"),
  document.getElementsByClassName("bx2"),
  document.getElementsByClassName("bx3"),
  document.getElementsByClassName("bx4")
];

for (let i = 1; i <= 4; i++) {
  colorOptArr[i].style.backgroundColor = `red`;
}
<section class="opt">
  <div class="colors bx1"></div>
  <div class="colors bx2"></div>
  <div class="colors bx3"></div>
  <div class="colors bx4"></div>
</section>

Why this code is not changing the color of the div and giving the error that can't change background of undefined value

Gykonik
  • 638
  • 1
  • 7
  • 24
  • `getElementS` is plural, it returns a *list* of elements. You have an array of arrays. Each of `colorOptArr[i]` is an array, not a single element. – deceze May 03 '23 at 07:33
  • 1
    Also, arrays are zero indexed; by starting `i` at `1`, you're skipping the first element. – deceze May 03 '23 at 07:34
  • @deceze An array of [`HTMLCollection`](https://developer.mozilla.org/en-US/docs/Web/API/HTMLCollection) instances (which are array-like, but not arrays). :-) – T.J. Crowder May 03 '23 at 07:34
  • @T.J.Crowder Let's not confuse the poor chap more than necessary. ;) – deceze May 03 '23 at 07:35
  • document.getElementsByClassName() returns an HTMLCollection, that is, it behaves like an array. let colorOptArr = [ document.getElementsByClassName("bx1"), document.getElementsByClassName("bx2"), document.getElementsByClassName("bx3"), document.getElementsByClassName("bx4") ]; for (let i = 0; i < colorOptArr.length; i++) { for (let j = 0; j < colorOptArr[i].length; j++) { colorOptArr[i][j].style.backgroundColor = "red"; } } – Zen Of Kursat May 03 '23 at 07:36
  • try `let colorOptArr = document.querySelectorAll(".colors");` – Rohad Bokhar May 03 '23 at 07:36
  • so how can I do it? – Dinesh Chandra Pandey May 03 '23 at 07:37
  • from this code I want to give different color to every div – Dinesh Chandra Pandey May 03 '23 at 07:38
  • ``` let colorOptArr = [ document.querySelectorAll(".bx1"), document.querySelectorAll(".bx2"), document.querySelectorAll(".bx3"), document.querySelectorAll(".bx4") ]; for (let i = 0; i < 4; i++) { colorOptArr[i].forEach(element => element.style["background-color"] = `red`); } ``` – ADasGH May 03 '23 at 07:44
  • 1
    @DineshChandraPandey - The [linked question's answers](https://stackoverflow.com/questions/10693845/what-do-queryselectorall-and-getelementsby-methods-return) tell you how to fix it. That's the point of closing a question as a duplicate. – T.J. Crowder May 03 '23 at 07:52

0 Answers0