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