Useful Javascript snippets

Test if an element exists before using it

var someEle = document.querySelector("#some_id"); 
if(typeof (someEle) != "undefined" && someEle != null){

Vanilla JS equivalent to jQuery.ready()

// vanilla js equivalent of jquery.ready
document.addEventListener("DOMContentLoaded", function() {
  // do stuff on page load


Quickly Enable/Disable Javascript (Chrome)

  • open developer tools
  • Cmd + Shift + p
  • type: javascript
  • click enable / disable Javascript

(writable) Global var


(writable) Global var (hack) in ES6 accessible from any file

An important note on Javascript modules and scope

module features are imported into the scope of a single script — they aren’t available in the global scope. Therefore, you will only be able to access imported features in the script they are imported into, and you won’t be able to access them from the JavaScript console, for example.  more here: Modules Mozilla


import * as cook from './cookie-functions.js';

Everything imported from cookie-functions.js is available/visile only in the script where the import is.