Home > Blockchain >  Uncaught TypeError: Cannot read properties of undefined (reading 'style')
Uncaught TypeError: Cannot read properties of undefined (reading 'style')

Time:09-27

I'm working on an HTML template I've two different color theme on that template dark/light. I want to create a functionality that if operating system has dark theme on then websites dark theme will be on by default but if operating system has light theme on then websites light theme will be on by default.

I've multiple logos for different sections so I grabbed them by their className and loop through them to display: block according to the color theme by JavaScript. But I'm getting an error in console but in the website code is running perfectly it's doing the same thing I wanted.

But the problem is when I'm writing my other functionalities they aren't working for this error.

ERROR MESSAGE

Uncaught TypeError: Cannot read properties of undefined (reading 'style')

MY JAVASCRIPT CODE

const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
const body = document.body;

function darkLogoToggle() {
  for (let i = 0; i <= darkLogos.length; i  ) {
    darkLogos[i].style.display = "block";
  }
}

function lightLogoToggle() {
  for (let i = 0; i <= lightLogos.length; i  ) {
    lightLogos[i].style.display = "block";
  }
}

if (prefersDarkScheme.matches) {
  body.classList.toggle("dark");
  darkLogoToggle();
} else {
  body.classList.toggle("light");
  lightLogoToggle();
}

CodePudding user response:

You need to iterate till last element only. So, correct condition should be i < darkLogos.length and i < lightLogos.length

const prefersDarkScheme = window.matchMedia("(prefers-color-scheme: dark)");
const body = document.body;
  
function darkLogoToggle() {
  for (let i = 0; i < darkLogos.length; i  ) {
    darkLogos[i].style.display = "block";
  }
}

function lightLogoToggle() {
  for (let i = 0; i < lightLogos.length; i  ) {
    lightLogos[i].style.display = "block";
  }
}

if (prefersDarkScheme.matches) {
  body.classList.toggle("dark");
  darkLogoToggle();
} else {
  body.classList.toggle("light");
  lightLogoToggle();
}
  • Related