Use querySelector() for the first element that matches a CSS selector, and querySelectorAll() for every match. The older getElementById(), getElementsByClassName() and getElementsByTagName() each select by one thing.
querySelector() returns the first match, or null if nothing matches. querySelectorAll() returns a static NodeList that does not change afterwards. Both accept any CSS selector, such as #myId .myClass, which makes them the most flexible choice.
getElementById() is the direct way to find a single element by its ID. getElementsByClassName() and getElementsByTagName() return a live HTMLCollection, which updates by itself as the DOM changes. That can surprise you in a loop that adds or removes matching elements.
// By ID
document.getElementById('myId');
// By class
document.getElementsByClassName('myClass');
document.querySelector('.myClass');
document.querySelectorAll('.myClass');
// By tag
document.getElementsByTagName('div');
// By CSS selector
document.querySelector('#myId .myClass');
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓