Node Types in the DOM #
Each point in the DOM tree is called a node, and nodes are generally categorized into three types:
- Element Node: Corresponds to an HTML tag.
- Text Node: Represents the text content inside an element.
- Comment Node: Represents an HTML comment (e.g.,
<!-- comment -->
).
The DOM provides two main types of node collections: HTMLCollection
and NodeList
.
HTMLCollection
: Contains only element nodes. It is a live collection, meaning it updates automatically when the DOM changes.NodeList
: Contains all node types and is a static collection, meaning it does not update automatically.
Common Methods of the Document Object #
Once you’re familiar with node types, you can start using the document
object’s built-in methods to manipulate elements.
Method | Return Type | Description |
---|---|---|
document.getElementById(id) |
Element |
Selects the first element with the given id |
document.getElementsByClassName(name) |
HTMLCollection |
Gets all elements with the specified class name |
document.getElementsByTagName(tag) |
HTMLCollection |
Gets all elements with the specified tag name (div , p , etc.) |
document.querySelector(selector) |
Element or null |
Returns the first element matching the CSS selector |
document.querySelectorAll(selector) |
NodeList |
Returns all elements matching the CSS selector |
document.createElement(tagName) |
Element |
Dynamically creates a new element node (e.g., createElement("button") ) |
document.createTextNode(text) |
Text |
Creates a text node, which can be inserted into an element |