DOM Manipulation APIs
The Document Object Model (DOM) is a programming interface for HTML and XML documents. It represents the page so that programs can change the document structure, style, and content. The DOM can be used to validate HTML, parse XML, and more. When a web page is loaded, the browser creates a DOM representation of the page.
What is the DOM?
The DOM is a tree structure where each node represents a part of the document. The root node is the document object, representing the entire HTML document.
- Elements: HTML tags like
<div>,<p>,<h1>. - Attributes: Properties of elements, like
id,class,src. - Text: The content within elements.
Accessing DOM Elements
JavaScript provides several methods to select elements from the DOM:
By ID: getElementById()
This method returns the element with the specified ID.
const mainTitle = document.getElementById('page-title');
console.log(mainTitle.textContent);
By Tag Name: getElementsByTagName()
This method returns a collection of all elements with the specified tag name.
const allParagraphs = document.getElementsByTagName('p');
for (let i = 0; i < allParagraphs.length; i++) {
console.log(allParagraphs[i].textContent);
}
By Class Name: getElementsByClassName()
This method returns a collection of all elements with the specified class name.
const highlightedItems = document.getElementsByClassName('highlight');
for (let i = 0; i < highlightedItems.length; i++) {
highlightedItems[i].style.color = 'blue';
}
By CSS Selector: querySelector() and querySelectorAll()
These are powerful methods that use CSS selectors to find elements. querySelector() returns the first matching element, while querySelectorAll() returns a NodeList of all matching elements.
// Get the first element with the class 'important'
const firstImportant = document.querySelector('.important');
// Get all list items within an element with ID 'menu'
const menuItems = document.querySelectorAll('#menu li');
menuItems.forEach(item => {
item.style.fontWeight = 'bold';
});
Modifying DOM Elements
Once you have accessed an element, you can change its properties, content, and style.
Changing Content: innerHTML and textContent
textContent: Sets or returns the text content of an element and its descendants. It's safer as it doesn't interpret HTML.innerHTML: Sets or returns the HTML content of an element. Use with caution due to potential security risks (XSS).
const introDiv = document.getElementById('introduction');
introDiv.textContent = 'This is the updated introduction text.';
const footerDiv = document.getElementById('footer');
footerDiv.innerHTML = '© 2023 MSDN Tutorials';
Changing Attributes: setAttribute() and getAttribute()
Modify or retrieve element attributes.
const myImage = document.getElementById('logo');
myImage.setAttribute('src', 'new-logo.png');
const currentSrc = myImage.getAttribute('src');
console.log('Image source is now:', currentSrc);
Changing Styles: style Property
Access and modify inline styles of an element.
const alertBox = document.getElementById('alert');
alertBox.style.backgroundColor = '#ffdddd';
alertBox.style.border = '1px solid red';
alertBox.style.padding = '10px';
alertBox.style.display = 'block'; // Make it visible
Creating and Appending Elements
You can dynamically add new elements to the page.
// Create a new paragraph element
const newPara = document.createElement('p');
// Set its content
newPara.textContent = 'This is a dynamically created paragraph!';
// Append it to the main content area
const mainContentDiv = document.querySelector('.main-content');
mainContentDiv.appendChild(newPara);
Removing Elements
Remove elements from the DOM.
const oldElement = document.getElementById('old-section');
if (oldElement) {
oldElement.parentNode.removeChild(oldElement);
// Or more modern: oldElement.remove();
}
Event Handling
DOM elements can respond to user interactions like clicks, mouseovers, and key presses. See the Events API tutorial for more details.
Conclusion
The DOM manipulation APIs are fundamental to creating interactive and dynamic web pages. By understanding how to select, modify, create, and remove elements, you can build sophisticated user interfaces.