1. document.getElementById()
The document.getElementById()
method is the simplest way to select an element by its unique id
attribute.
const element = document.getElementById('myElementId');
Return type
This method returns the element object that matches the specified id
, or null
if no element is found.
2. document.getElementsByClassName()
The document.getElementsByClassName()
method selects all elements that have a specified class name.
let elements = document.getElementsByClassName('myClassName');
Return type
It returns an HTMLCollection, which is similar to an array. Even if there is only one such element, the result will still be an HTMLCollection.
3. document.getElementsByTagName()
The document.getElementsByTagName()
method selects all elements with a specified tag name, such as div
, p
, span
, etc.
let elements = document.getElementsByTagName('div');
Return type
This method returns an HTMLCollection
4. document.querySelector()
The document.querySelector()
method allows for more flexibility as it selects the first element that matches a specified CSS selector.
let element = document.querySelector('.myClassName');
Return type
This method is incredibly powerful because it supports all CSS selector syntax. If there are multiple elements with this class, only the first one will be selected. If it doesn’t find any element, it will return null.
5. document.querySelectorAll()
The document.querySelectorAll()
method is similar to querySelector()
, but instead of returning just the first matching element, it returns all elements that match the specified CSS selector.
let elements = document.querySelectorAll('.myClassName');
Return type
The return type is a NodeList, which is a collection of nodes.