Contents
DOM Manipulation
The Document Object Model (DOM) is a representation of the structure of an HTML document. It allows JavaScript to interact with and manipulate web pages dynamically. Through DOM manipulation, you can change the structure, content, and style of a webpage.
In this guide, we’ll cover how to select elements, modify them, and handle events using JavaScript.
Selecting Elements
To manipulate elements in the DOM, you first need to select them. JavaScript provides various methods for selecting HTML elements.
1.1 Selecting Elements by ID
getElementById()
: Selects an element by itsid
attribute.
const header = document.getElementById('main-header');
1.2 Selecting Elements by Class Name
getElementsByClassName()
: Returns a live HTMLCollection of all elements with the specified class name(s). You can access elements in this collection using array-like indexing.
const items = document.getElementsByClassName('item');
console.log(items[0]); // Access the first element with class 'item'
1.3 Selecting Elements by Tag Name
getElementsByTagName()
: Returns a live HTMLCollection of all elements with the specified tag name.
const paragraphs = document.getElementsByTagName('p');
1.4 Selecting Elements Using Query Selectors
querySelector()
: Returns the first element that matches the specified CSS selector.
const mainTitle = document.querySelector('.title');
const firstItem = document.querySelector('#item-list li');
querySelectorAll()
: Returns a NodeList of all elements that match the specified CSS selector.
const allItems = document.querySelectorAll('.item');
allItems.forEach(item => {
console.log(item.textContent);
});
Modifying Elements
Once you have selected an element, you can modify its content, attributes, and styles.
2.1 Changing Content
textContent
: Sets or returns the text content of an element.
const header = document.getElementById('main-header');
header.textContent = "Welcome to My Website!";
innerHTML
: Sets or returns the HTML content inside an element, allowing you to include HTML tags.
const content = document.querySelector('.content');
content.innerHTML = 'This is a new paragraph.
';
2.2 Changing Attributes
setAttribute()
: Adds a new attribute or changes the value of an existing attribute on an element.
const link = document.querySelector('a');
link.setAttribute('href', 'https://www.example.com');
getAttribute()
: Returns the value of a specified attribute.
const linkUrl = link.getAttribute('href');
removeAttribute()
: Removes an attribute from an element.
link.removeAttribute('target');
2.3 Changing Styles
style
: Allows you to set inline styles for an element.
const header = document.querySelector('h1');
header.style.color = 'blue';
header.style.fontSize = '2em';
- Adding/Removing Classes: Use
classList
to add, remove, or toggle classes on an element.
const box = document.querySelector('.box');
box.classList.add('active'); // Add a class
box.classList.remove('hidden'); // Remove a class
box.classList.toggle('highlight'); // Toggle a class
Event Handling
Events are actions or occurrences that happen in the browser, like a user clicking a button, pressing a key, or loading a page. You can use JavaScript to listen for these events and respond to them.
3.1 Adding Event Listeners
addEventListener()
: Attaches an event handler to an element.
const button = document.querySelector('#myButton');
button.addEventListener('click', function() {
alert('Button was clicked!');
});
3.2 Common Events
Mouse Events:
click
,dblclick
,mousedown
,mouseup
,mouseenter
,mouseleave
, etc.
const box = document.querySelector('.box');
box.addEventListener('mouseenter', () => {
box.style.backgroundColor = 'lightblue';
});
box.addEventListener('mouseleave', () => {
box.style.backgroundColor = 'white';
});
- Keyboard Events:
keydown
,keypress
,keyup
.
document.addEventListener('keydown', (event) => {
console.log(`Key pressed: ${event.key}`);
});
Form Events:
submit
,change
,focus
,blur
.
const form = document.querySelector('form');
form.addEventListener('submit', (event) => {
event.preventDefault(); // Prevents the form from submitting
console.log('Form submitted!');
});
3.3 Removing Event Listeners
To remove an event listener, you must reference the function you used when adding the event listener.
function handleClick() {
alert('Button clicked!');
}
button.addEventListener('click', handleClick);
button.removeEventListener('click', handleClick);
3.4 Event Object
When an event occurs, the event object is automatically passed to the event handler function. This object contains information about the event, such as the target element, the type of event, and any additional details.
document.querySelector('#myButton').addEventListener('click', (event) => {
console.log(event.target); // Logs the element that was clicked
console.log(event.type); // Logs the event type ('click')
});
Summary
DOM manipulation in JavaScript allows you to interact with and modify the content, structure, and style of a webpage. You can select elements using various methods like getElementById
, querySelector
, and querySelectorAll
. Once selected, elements can be modified by changing their content, attributes, or styles. JavaScript also enables event handling, allowing you to respond to user interactions, such as clicks, key presses, and form submissions. By mastering DOM manipulation, you can create dynamic and interactive web applications.