The Document Object Model (DOM)
The Document Object Model (DOM) is a programming interface for web documents that represents the structure of a web page. It treats an HTML or XML document as a tree structure, where each node is an object representing a part of the document.
Selecting and Manipulating Elements
JavaScript provides several methods to select and manipulate elements in the DOM:
Selecting Elements
document.getElementById(id)
: Selects an element by its unique ID.document.getElementsByTagName(name)
: Selects elements by tag name.document.getElementsByClassName(className)
: Selects elements by class name.document.querySelector(selector)
: Selects the first element matching a CSS selector.document.querySelectorAll(selector)
: Selects all elements matching a CSS selector.
Manipulating Elements
Once you have selected an element, you can manipulate it using various properties and methods:
element.innerHTML
: Sets or gets the HTML content inside an element.element.textContent
: Sets or gets the text content of an element.element.setAttribute(name, value)
: Sets an attribute value for the element.element.getAttribute(name)
: Gets the value of an attribute for the element.element.classList.add(className)
: Adds a class to the element.element.classList.remove(className)
: Removes a class from the element.element.style.property = value
: Sets an inline style property for the element.
Creating and Removing Elements
You can dynamically create and remove elements in the DOM using the following methods:
document.createElement(tagName)
: Creates a new element with the specified tag name.parentNode.appendChild(newNode)
: Adds a new child node to the end of the children of a specified parent node.parentNode.insertBefore(newNode, referenceNode)
: Inserts a new node before a reference node.parentNode.removeChild(node)
: Removes a child node from the DOM tree.node.replaceChild(newNode, oldNode)
: Replaces a child node with a new node.
Working with Events
Events are actions or occurrences that happen in the browser, such as clicks, key presses, or form submissions. JavaScript allows you to listen for and handle these events using event listeners.
const button = document.getElementById("myButton");
button.addEventListener("click", function() {
console.log("Button clicked!");
});
In the next chapter, we'll explore JavaScript in the browser environment, including the Window object, timers, cookies, web storage, and AJAX.