Selecting Elements in the DOM
Thi?u Quang Khoa
?Performance Tuning at Wecommit Vi?t Name | Oracle Database | Software Engineering Major at FPT University | 7.0 IETLS?
Definition of the DOM and Basic Concepts
The DOM, which stands for Document Object Model, represents the structured hierarchy of an HTML document in the form of a tree-like structure, with each HTML element as a node in this tree. The browser generates this tree of nodes, and each node possesses unique properties and methods that can be manipulated using JavaScript.
In the DOM:
Selecting Elements in the DOM
1. getElementById
Use this method to select an element by its unique id attribute.
// HTML: <div id="myElement">Content</div>
let element = document.getElementById('myElement');
console.log(element); // Output: <div id="myElement">Content</div>
2. getElementsByTagName
Use this method to select all elements that match a specified tag name. It returns an HTMLCollection.
// HTML: <p>Paragraph 1</p> <p>Paragraph 2</p>
let paragraphs = document.getElementsByTagName('p');
console.log(paragraphs); // Output: HTMLCollection of all <p> elements
领英推荐
3. getElementsByClassName
Use this method to select elements by their class name. It returns an HTMLCollection.
// HTML: <div class="myClass">Div 1</div> <div class="myClass">Div 2</div> let elements = document.getElementsByClassName('myClass'); console.log(elements); // Output: HTMLCollection of all elements with class "myClass"
4. getElementsByName
Use this method to select elements by their name attribute. It returns a NodeList.
// HTML: <input type="text" name="username"> let inputs = document.getElementsByName('username'); console.log(inputs); // Output: NodeList of elements with the name "username"
5. querySelector
Use this method to select the first element that matches a CSS selector.
// HTML: <div class="myClass" id="unique">Div</div> let element = document.querySelector('.myClass'); console.log(element); // Output: The first element with class "myClass"
6. querySelectorAll
Use this method to select all elements that match a CSS selector. It returns a static NodeList.
// HTML: <div class="myClass">Div 1</div> <div class="myClass">Div 2</div> let elements = document.querySelectorAll('.myClass'); console.log(elements); // Output: NodeList of all elements with class "myClass"