HTML DOM Manipulation and Event Listeners in JavaScript
HTML DOM (Document Object Model) Manipulation
The HTML DOM is a programming interface for web documents. It represents the structure of a document as a tree of objects, as the image shown below, which allows scripts to update the content, structure, and style of a document.
Finding HTML Elements
To manipulate HTML elements, you first need to find or select them. There are several methods to find HTML elements in the DOM:
By ID
Use document.getElementById(id)
to find an element by its unique ID.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML DOM Selector By ID Example</title>
</head>
<body>
<p id="demo">Hello World!</p>
<script>
let element = document.getElementById('demo');
console.log(element); // Output: <p id="demo">Hello World!</p>
</script>
</body>
</html>
By Class Name
Use document.getElementsByClassName(className)
to find elements by their class name. This returns a live HTMLCollection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML DOM Selector By Class Name Example</title>
</head>
<body>
<p class="example">First</p>
<p class="example">Second</p>
<script>
<p class="example">First</p>
<p class="example">Second</p>
</script>
</body>
</html>
By Tag Name
Use document.getElementsByTagName(tagName)
to find elements by their tag name. This also returns a live HTMLCollection.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML DOM Selector By Tag Name Example</title>
</head>
<body>
<p>First</p>
<p>Second</p>
<script>
let elements = document.getElementsByTagName('p');
console.log(elements); // Output: HTMLCollection [p, p]
</script>
</body>
</html>
By CSS Selector
Use document.querySelector(selector)
to find the first element that matches a specified CSS selector, or document.querySelectorAll(selector)
to find all matching elements. This returns a static NodeList.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML DOM Selector By CSS Selector Example</title>
</head>
<body>
<p class="example">First</p>
<p class="example">Second</p>
<script>
let element = document.querySelector('.example');
console.log(element); // Output: <p class="example">First</p>
let elements = document.querySelectorAll('.example');
console.log(elements); // Output: NodeList [p.example, p.example]
</script>
</body>
</html>
Changing HTML Content
Once you've selected an element, you can change its HTML content using the innerHTML
property.
innerHTML
The innerHTML
property sets or returns the HTML content inside an element.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML DOM Selector By CSS Selector Example</title>
</head>
<body>
<p id="demo">Hello World!</p>
<script>
let element = document.getElementById('demo');
element.innerHTML = 'Hello JavaScript!';
console.log(element.innerHTML); // Output: Hello JavaScript!
</script>
</body>
</html>
Changing HTML Style
You can change the style of an HTML element using the style
property.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML DOM Selector By CSS Selector Example</title>
</head>
<body>
<p id="demo">Hello World!</p>
<script>
let element = document.getElementById('demo');
element.style.backgroundColor = 'yellow';
element.style.color = 'red';
element.style.fontSize = '20px';
element.style.fontWeight = 'bold';
</script>
</body>
</html>
Example using all these methods
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>HTML DOM Selector By CSS Selector Example</title>
<style>
.example {
color: blue;
}
</style>
</head>
<body>
<p id="demo">Hello World!</p>
<p class="example">This is a test.</p>
<p class="example">Another test.</p>
</body>
</html>
// Finding an element by ID
let demoElement = document.getElementById('demo');
demoElement.innerHTML = 'Hello JavaScript!';
demoElement.style.backgroundColor = 'yellow';
// Finding elements by class name
let exampleElements = document.getElementsByClassName('example');
for (let i = 0; i < exampleElements.length; i++) {
exampleElements[i].style.color = 'green';
}
// Finding elements by tag name
let pElements = document.getElementsByTagName('p');
for (let i = 0; i < pElements.length; i++) {
pElements[i].style.fontSize = '18px';
}
// Finding an element using querySelector
let firstExampleElement = document.querySelector('.example');
firstExampleElement.textContent = 'First example changed.';
// Finding elements using querySelectorAll
let allExampleElements = document.querySelectorAll('.example');
allExampleElements.forEach(element => {
element.style.fontWeight = 'bold';
});
The whole purpose behind understanding and learning DOM manipulation is to change and update and modify our elements and their styles dynamically on the runtime.
Event Listeners
What is an Event?
In JavaScript, an event is an action or occurrence recognized by the software, often generated by the user. Examples include clicking a button, loading a webpage, resizing a window, or pressing a key. The event can trigger a response in the form of an event handler or event listener.
How to Use Event Listeners
Event listeners are used to execute code in response to an event. You attach an event listener to an HTML element, and when the specified event occurs, the listener executes a function.
Adding Event Listeners
The most common method to add an event listener is addEventListener()
.
syntax
element.addEventListener(event, function, useCapture);
event: A string representing the event type to listen for (e.g., 'click', 'mouseover').
function: The function to execute when the event occurs.
useCapture: Optional. A boolean value that specifies whether the event should be executed in the capturing or bubbling phase. Default is
false
(bubbling phase).
Click Event
// Select the button element
let button = document.getElementById('myButton');
// Define the event handler function
let handleClick = () => {
alert('Button was clicked!');
}
// Add the event listener to the button
button.addEventListener('click', handleClick);
Mouseover Event
// Select the paragraph element
let paragraph = document.getElementById('myParagraph');
// Define the event handler function
let handleMouseOver = () => {
paragraph.style.color = 'red';
}
// Add the event listener to the paragraph
paragraph.addEventListener('mouseover', handleMouseOver);
Event Object
When an event occurs, the event handler receives an event object containing information about the event. This object is often passed as an argument to the event handler function.
// Select the button element
let button = document.getElementById('myButton');
// Define the event handler function
let handleClick = (event) => {
console.log('Event type:', event.type); // Output: click
console.log('Event target:', event.target); // Output: <button id="myButton">Click me</button>
}
// Add the event listener to the button
button.addEventListener('click', handleClick);
Logging out the event
object of an event listeners will give you a large object with many properties to play with, if you want to have a deep understanding of each events just to console.log(event)
on each event listeners.
Subscribe to my newsletter
Read articles from Syed Aquib Ali directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Syed Aquib Ali
Syed Aquib Ali
I am a MERN stack developer who has learnt everything yet trying to polish his skills 🥂, I love backend more than frontend.