title: document.querySelector() on elements not in DOM?
body: <p>I'm working on a website, with jQuery but I'm trying to not use it anymore. In jQuery you can add an even listener on a element that wasn't on the website or wasn't created yet and no problem. I have elements that are only on the DOM when you're logged in, and I only have one JS file for the whole website.</p>
  
  <p>Problem is, for example, when you're logged in you can't see the "log in" button, it's not even in the DOM, but it still have the event listener in the code, no error on the console, script runs well.</p>
  
  <pre><code>$("#logInButton").on("click", somefunction);
  </code></pre>
  
  <p>But, using <code>document.querySelector("#logInButton").onclick = somefunction</code> and being logged in already, it throws an error because <code>document.querySelector("#logInButton")</code> is null.</p>
  
  <p>I can do like:</p>
  
  <pre><code>let logInButton = document.querySelector("#logInButton");
  
  logInButton ? logInButton.onclick = somefunction : "";
  </code></pre>
  
  <p>And it works well, but I know it's not a good practice. Any workaround or improvement to that, not  using jQuery?</p>
  
  <p><a href="https://jsfiddle.net/p2qbLs2m/" rel="nofollow noreferrer">JSFiddle if what happens. (See console)</a></p>