* Add JS tips section to frontend documentation
* Replace document.getElementsByTagName('body') with document.body
* Replace querySelectorAll with faster selecting methods where appropriate
* Replace querySelector with faster selecting methods where appropriate
* Fix typo
* Fix forEach and getElementsByClassName
* Change querySelector* to faster methods in erb files
* Change querySelector* to faster methods in ruby files
* Fix runkit tag
* Various fixes
* Update app/assets/javascripts/initializers/initializeEllipsisMenu.js
Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>
* Update app/assets/javascripts/utilities/slideSidebar.js
Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>
* Commenting out flaky spec
Co-authored-by: Ridhwana <Ridhwana.Khan16@gmail.com>
1.8 KiB
1.8 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.