JavaScript Selectors
About JavaScript Selector
JavaScript selectors are functions used to select HTML elements so that we can read/access or modify them using JavaScript. The DOM (Document Object Model) provides these methods to select elements from an HTML document.
Why Use Selectors?
Selectors are essential for interacting with the DOM. They allow you to select elements based on their ID, class, tag name, or other attributes, enabling you to read or modify their content, styles, and behavior dynamically.
Mastering JavaScript selectors is fundamental to effective DOM manipulation.
Most Common JavaScript Selector Methods
JavaScript provides several methods to select elements from the DOM. Here are some of the most commonly used selector methods:
Basic Selectors
-
getElementById(): Selects a single element by its unique
idattribute. - getElementsByClassName(): Selects all elements that have a specific class name.
- getElementsByTagName(): Selects all elements with a specific tag name (e.g., div, p, a).
Advanced Modern Selectors
- querySelector(): Selects the first element that matches a CSS-style selector.
- querySelectorAll(): Selects all elements that match a CSS-style selector.
getElementById('id') Method
The getElementById() method is used to select a single HTML element by its unique id attribute. It returns the first element with the specified id or null if no such element exists.
This method is commonly used to manipulate or retrieve information from a specific element in the DOM.
id should be unique within an HTML document. This method is very efficient for targeting a specific element.
Here is an example of how to use the getElementById() method: