DOM Mastery How to select Elements in JavaScript

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.

Resources

minhajulalam.cse@gmail.com

With over four years of experience in software engineering, I’m Minhajul Alam, a passionate coder who thrives on both technical challenges and product management. My journey in software development has been driven by a deep love for coding and a continual desire to learn and grow. I am dedicated to crafting innovative solutions and improving user experiences, always staying curious about the latest technologies and methodologies. My commitment to excellence in both coding and product management allows me to contribute effectively to the creation of impactful and user-centric software products.