2.1 KiB
2.1 KiB
| title |
|---|
| Tips |
Tips
About query selectors
JavaScript has many different query selectors, some seemingly interchangeable, for example:
document.headanddocument.bodydocument.getElementById,document.getElementsByClassNameanddocument.getElementsByTagNamedocument.querySelectoranddocument.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.headoverdocument.getElementsByTagName('head') - to access the body of the document, use
document.bodyoverdocument.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.
Resources
- Forem PR 6380
- Why is getElementsByTagName() faster than querySelectorAll()?
- What is the difference between querySelectorAll and getElementsByTagName?
Service workers in development
By default our service worker code doesn't run in development.
If you're planning to do any work around service workers you'll need to enable
them by setting the SKIP_SERVICEWORKERS environment variable to "false".