title: Uncaught TypeError: Cannot read property 'offsetTop' of null
body: <p>I am using HTML, CSS and JavaScript to create a web page with a sticky and responsive navigation bar. I created the responsive navigation bar and am trying to make it sticky as well. The issue is that it's not sticky and shows error:
  Uncaught TypeError: Cannot read property 'offsetTop' of null</p>
  
  <p>HTML code:</p>
  
  <pre><code>&lt;div class="topnav" id="myTopnav"&gt;
  &lt;a href="#home" class="active"&gt;Home&lt;/a&gt;
  &lt;a href="#career"&gt;Careers&lt;/a&gt;
  &lt;a href="#fellowship"&gt;About Us&lt;/a&gt;
  &lt;a href="javascript:void(0);" class="icon" onclick="myFunctionForResponsive()"&gt;
      &lt;i class="fas fa-bars"&gt;&lt;/i&gt;
  &lt;/a&gt;
  &lt;/div&gt;
  </code></pre>
  
  <p>JavaScript code:</p>
  
  <pre><code>// When the user scrolls the page, execute myFunction 
  window.onscroll = function() {myFunctionForSticky()};
  
  // Get the navbar
  var navbar = document.getElementById("myTopnav");
  
  // Get the offset position of the navbar
  var sticky = navbar.offsetTop;
  
  // Add the sticky class to the navbar when you reach its scroll position. 
  Remove "sticky" when you leave the scroll position
  function myFunctionForSticky() {
      if(window.pageYOffset &gt;= sticky){
      console.log("window.pageYOffset &gt;= sticky");
  }
  else{
      console.log("Not window.pageYOffset &gt;= sticky");
  }
   if (window.pageYOffset &gt;= sticky) {
      navbar.classList.add("sticky");
    } else {
      navbar.classList.remove("sticky");  
    }
  }
  
  /*Toggle between adding and removing the "responsive" class to topnav
  when the user clicks on the icon*/
  
  function myFunctionForResponsive() {
      var x = document.getElementById("myTopnav");
      if (x.className === "topnav") {
          x.className += " responsive";
      } else {
          x.className = "topnav";
      }
  }
  </code></pre>
  
  <p>If I am taking class instead of id then it's showing the error: 
  Uncaught TypeError: Cannot read property 'remove' of undefined</p>