DEV Community

Discussion on: Snippets for Vanilla JS Coding

Collapse
 
kapouer profile image
Jérémy Lal

Hi, ignoring with which document you're working is a quick way to bang your head to the wall. Always keep a reference to which document you're in:

HTMLDocument.prototype.$ = HTMLDocument.prototype.querySelector
HTMLDocument.prototype.$$ = HTMLDocument.prototype.querySelectorAll

A shorthand for document, why not:

window.doc = window.document
doc.$("body")
doc.$$("script")

Everything's nice now, you need to work off-line ?

var offdoc = doc.cloneNode()
// mind that some browsers don't create offdoc.documentElement so
if (!offdoc.documentElement) offdoc.appendChild(offdoc.createElement('html'))
offdoc.documentElement.innerHTML = '<head></head><body></body>'
// this won't load the file
offdoc.head.insertAdjacentHTML('beforeEnd', '<script src="toto.js"></script>')
// and this still works
offdoc.$('script')
Collapse
 
learosema profile image
Lea Rosema (she/her) • Edited

In this case, another option is to define another shortcut for documents other than document. For example, you can move the $ function definition inside a function that takes a document as a parameter:

function insertScriptIntoDocument(doc, jsfile) { 
  const $o = doc.querySelector.bind(doc)
  const script = document.createElement('script')
  script.setAttribute('src', jsFile)
  $o`head`.insertAdjacentHTML('beforeEnd', script)
}