The Document Object Model (DOM) is a programming interface for web documents. It represents the page so that programs can change the document structure, style, and content. The DOM represents the document as nodes and objects.
8.1. What is the DOM?
When a web page is loaded, the browser creates a Document Object Model of the page. It's a tree-like structure where each HTML element, attribute, and text is a "node." JavaScript can then interact with this tree.
- Document: The root of the DOM tree, representing the entire HTML document.
- Elements: HTML tags (e.g.,
<body>
, <h1>
, <p>
, <div>
).
- Attributes: Properties of HTML elements (e.g.,
id
, class
, src
).
- Text: The content inside HTML elements.
8.2. Accessing HTML Elements
To manipulate an HTML element with JavaScript, you first need to "select" or "get" a reference to it.
-
document.getElementById('idName')
: Selects a single element by its unique id
attribute.
<div id="myDiv"></div>
<script>
const myDiv = document.getElementById('myDiv');
console.log(myDiv);
</script>
-
document.getElementsByClassName('className')
: Selects all elements with a specific class
name. Returns an HTMLCollection (live list).
<p class="intro"></p><p class="intro"></p>
<script>
const intros = document.getElementsByClassName('intro');
console.log(intros[0]); // Access first element
</script>
-
document.getElementsByTagName('tagName')
: Selects all elements with a specific HTML tag name. Returns an HTMLCollection.
<span></span><span></span>
<script>
const spans = document.getElementsByTagName('span');
console.log(spans.length);
</script>
-
document.querySelector('CSS_selector')
: Selects the first element that matches a specified CSS selector.
<div class="container"><p id="firstPara"></p><p></p></div>
<script>
const firstParagraph = document.querySelector('#firstPara'); // By ID
const container = document.querySelector('.container'); // By Class
const anyParagraph = document.querySelector('p'); // First <p>
console.log(firstParagraph);
</script>
-
document.querySelectorAll('CSS_selector')
: Selects all elements that match a specified CSS selector. Returns a NodeList (static list).
<p class="item"></p><p class="item"></p>
<script>
const items = document.querySelectorAll('.item');
items.forEach(item => console.log(item)); // NodeList can be iterated with forEach
</script>
8.3. Modifying HTML Elements
Once you have a reference to an element, you can change its content, attributes, or style.
-
element.textContent
: Gets or sets the text content of an element (plain text).
myDiv.textContent = "New text content!";
-
element.innerHTML
: Gets or sets the HTML content of an element (parses HTML tags). Use with caution to prevent XSS vulnerabilities.
myDiv.innerHTML = "<strong>Bold</strong> new content.";
-
element.style.propertyName
: Sets inline CSS styles. Property names are camelCased (e.g., backgroundColor
for background-color
).
myDiv.style.backgroundColor = 'lightblue';
myDiv.style.fontSize = '20px';
-
element.setAttribute('attribute', 'value')
: Sets the value of an attribute.
const img = document.querySelector('img');
img.setAttribute('src', 'new-image.jpg');
-
element.classList.add('className')
, remove()
, toggle()
: Manipulate CSS classes.
myDiv.classList.add('highlight');
myDiv.classList.remove('old-class');
myDiv.classList.toggle('active'); // Adds if not present, removes if present
8.4. Adding and Removing HTML Elements
You can dynamically create new elements and add them to the DOM, or remove existing ones.
-
document.createElement('tagName')
: Creates a new HTML element node.
const newParagraph = document.createElement('p');
newParagraph.textContent = "This is a dynamically created paragraph.";
-
parentNode.appendChild(childNode)
: Adds a node as the last child of a specified parent node.
document.body.appendChild(newParagraph); // Adds to the end of the body
-
parentNode.removeChild(childNode)
: Removes a specified child node from the DOM.
const elementToRemove = document.getElementById('oldElement');
if (elementToRemove) {
elementToRemove.parentNode.removeChild(elementToRemove);
}
8.5. Handling Events (Event Listeners)
Events are actions that happen on a web page (e.g., a user clicking a button, a page loading, a key press). JavaScript can respond to these events using event listeners.
-
element.addEventListener('eventName', functionName)
: Attaches an event handler function to an element.
<button id="myButton">Click Me</button>
<script>
const myButton = document.getElementById('myButton');
function handleClick() {
console.log("Button clicked!");
myButton.textContent = "Clicked!";
}
myButton.addEventListener('click', handleClick);
// You can also use an anonymous function directly:
// myButton.addEventListener('mouseover', function() {
// console.log("Mouse over button!");
// });
</script>
Common events include click
, mouseover
, mouseout
, keydown
, keyup
, submit
, load
, scroll
, etc.
With a grasp of Arrays, Objects, and the DOM, you now have the tools to manage complex data structures and make your web pages interactive. In the next part, we'll delve into more advanced JavaScript concepts, including asynchronous programming and modern ES6+ features.