title: If element is not present on page why is JavaScript throwing an error?
body: <p>My scenario is that I have one JS file which is being used on two HTML pages. One has a <code>button</code> with <code>id="a"</code> and the other doesn't have it. I have attached an event on <code>id="a"</code> by doing this.</p>
  
  <pre><code>document.getElementbyId("a").onclick = function () { .. }
  </code></pre>
  
  <p>My problem is when I run second file which doesn't have the <code>button</code> with <code>id="a"</code> and it throws the error </p>
  
  <pre><code>TypeError: document.getElementbyId(...) is null
  </code></pre>
  
  <p>which causes some unexpected behaviour! Is there any way to keep using just one JS file or should I separate the JS file for every html page?</p>
  
  <p>I read a question on StackOverflow <a href="https://stackoverflow.com/questions/3709604/why-doesnt-jquery-bomb-if-your-selector-object-is-invalid">here</a> which is about why jQuery doesn't throw an error if the selector is invalid. I need same or similar functionality with vanilla JavaScript.</p>