JavaScript has many different query selectors, some seemingly interchangeable, for example:
document.head
and document.body
document.getElementById
, document.getElementsByClassName
and document.getElementsByTagName
document.querySelector
and document.querySelectorAll
Knowing which to use for optimal performance depends on the situation, but a good rule of thumb is:
document.head
over document.getElementsByTagName('head')
document.body
over document.getElementsByTagName('body')
document.getElementById('id')
over document.querySelector('#id')
document.getElementsByClassName('className')[0]
over document.querySelector('.className')
document.getElementsByClassName('className')
over document.querySelectorAll('.className')
document.getElementsByTagName('tagName')[0]
over document.querySelector('tagName')
document.getElementsByTagName('tagName')
over document.querySelectorAll('tagName')
In most cases querySelector
and querySelectorAll
should be used only on selectors more sophisticated than a simple id, class or tag name.