最新消息:Welcome to the puzzle paradise for programmers! Here, a well-designed puzzle awaits you. From code logic puzzles to algorithmic challenges, each level is closely centered on the programmer's expertise and skills. Whether you're a novice programmer or an experienced tech guru, you'll find your own challenges on this site. In the process of solving puzzles, you can not only exercise your thinking skills, but also deepen your understanding and application of programming knowledge. Come to start this puzzle journey full of wisdom and challenges, with many programmers to compete with each other and show your programming wisdom! Translated with DeepL.com (free version)

css - Cannot set property 'className' of null at setThemeFromCookie

matteradmin5PV0评论

I am coding in WordPress to make a button to toggle body class from light-mode to dark-mode. i was experimenting with trying to add a cookie so that the preference is remembered for the browser. But i receive a error Cannot set property className of null at setThemeFromCookie.

moreover clicking the button gives another error (index):486 Uncaught TypeError: Cannot read property 'className' of null at togglePageContentLightDark

My url is you can see the button in blue color located in footer

JS follows

 function togglePageContentLightDark() {
      var body = document.getElementById('body')
      var currentClass = body.className
      var newClass = body.className == 'dark-mode' ? 'light-mode' : 'dark-mode'
      body.className = newClass

  document.cookie = 'theme=' + (newClass == 'light-mode' ? 'light' : 'dark')
  console.log('Cookies are now: ' + document.cookie)
}

function isDarkThemeSelected() {
  return document.cookie.match(/theme=dark/i) != null
}

function setThemeFromCookie() {
  var body = document.getElementById('body')
  body.className = isDarkThemeSelected() ? 'dark-mode' : 'light-mode'
}

(function() {
  setThemeFromCookie()
})();

HTML for button

<button type="button" name="dark_light" onclick="togglePageContentLightDark()" title="Toggle dark/light mode">
Post a comment

comment list (0)

  1. No comments so far