Advertisement
Google Ad Slot: content-top
JS Access Dom
JavaScript provides several methods to interact with and manipulate the Document Object Model (DOM). The DOM represents the structure of a web page as a hierarchical tree of elements, and these methods allow you to access specific parts of the document for dynamic updates.
Method |
Returns |
Live/Static |
Use Case |
|---|---|---|---|
Single element |
Live |
Best for accessing unique elements by |
|
HTMLCollection |
Live |
Access multiple elements with the same class. |
|
HTMLCollection |
Live |
Access elements by their tag name. |
|
Single element |
Static |
Access the first element matching a CSS selector. |
|
NodeList |
Static |
Access all elements matching a CSS selector. |
Accessing by id document.getElementById()
- Retrieves an element by its unique
idattribute. - Returns: A single element or
nullif not found.
Accessing by Class document.getElementByClassName()
- Retrieves all elements with a specified class name.
- Returns: A live HTMLCollection (like an array, but not exactly).
Accessing by Tag Name document.getElementByTagName()
- Retrieves all elements with a specified tag name.
- Returns: A live HTMLCollection.
Accessing by CSS Selectors Single Element document.querySelector()
- Retrieves the first matching element based on a CSS selector.
- Returns: A single element or
nullif not found.
Accessing by CSS Selectors Multiple Elements document.querySelectorAll()
- Retrieves all matching elements based on a CSS selector.
- Returns: A static NodeList (not live).
Looping Through Multiple Elements:
When accessing multiple elements (e.g., using getElementsByClassName or querySelectorAll), you can loop through them to perform actions: