Before you can change anything on a web page, you must first select the element you want to work with.
JavaScript provides several methods to select HTML elements from the DOM. Once an element is selected, you can change its text, style, attributes, or behavior.
Learning how to select elements is the foundation of all DOM manipulation.
Common Ways to Select Elements
- getElementById() – selects by id
- getElementsByClassName() – selects by class
- getElementsByTagName() – selects by tag name
- querySelector() – selects first matching element
- querySelectorAll() – selects all matching elements
These methods help you target exactly what you want on the page.
This method selects an element using its unique id attribute.
It is the fastest and most commonly used way to select elements.
This method selects all elements that share the same class name.
It returns a collection of elements, not just one.
The querySelector method allows you to use CSS-style selectors to pick elements easily.
By mastering element selection, students gain the power to control and manipulate any part of a web page using JavaScript.