未捕获的TypeError:切换html元素时无法读取null的属性'classList'

时间:2018-12-11 17:08:09

标签: javascript html

<body>
   <button class="openNav" onclick="toggleSideBar()"><i class="fas fa-bars"></i> 
  </button>
   <nav>
      <a href="#">Home</a>
      <a href="#">About</a>
      <a href="#">The Team</a>
      <a href="#">Contact</a>
   </nav>
   <div id="sidebar">
    <ul>
    <li>cat1</li>
    <li>cat1</li>
    <li>cat1</li>
    <li>cat1</li>
    </ul>
   </div>

   </body>
    <script src="resources/javascript/main.js"></script>
    <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"> 
   </script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js"> 
   </script>

   <script>
     function toggleSideBar(){
      console.log("inside toggleland");
      document.getElementById("sideBar").classList.toggle('active');
     }
   </script>
  

无法运行此代码。   出现了JavaScript错误“未捕获的TypeError:无法读取HTMLButtonElement.onclick上toggleSideBar处的null属性'classList'> null”

2 个答案:

答案 0 :(得分:1)

sideBar中用sidebar替换getElementById。您没有ID为sideBar的元素。

答案 1 :(得分:0)

id为<?xml version="1.0" encoding="utf-8"?> <set xmlns:android="http://schemas.android.com/apk/res/android"> <alpha android:fromAlpha="1.0" android:toAlpha="1.0" android:duration="250" /> </set> ,而您选择的驼峰ID为sidebar,请尝试sideBar