Lecture Note Of Day
10
DOM Manipulation
Objective:
By the end of this
session, students will understand how to interact with HTML elements using
JavaScript through the Document Object Model (DOM). They will learn
how to select elements, change their content and style, and handle events like
click and hover.
Introduction to DOM (Document Object Model)
When a web page is loaded, the browser creates a Document Object Model of the page.
The HTML DOM model
is constructed as a tree of Objects.
The Document
Object Model (DOM) is a programming interface for web documents. It
represents the page so that programs can manipulate the structure, style, and
content of the page. The DOM is essentially a tree-like structure where each
element on the webpage (like paragraphs, headings, images, links) is a node in
the tree.
HTML DOM tree of objects
Key Concepts of the DOM:
1. Document:
Represents the entire HTML page.
2. Elements:
Each HTML tag (e.g., <h1>, <p>, <div>) is an element in the
DOM.
3. Nodes:
Every element, text, and attribute in an HTML document is a node. There are
different types of nodes, such as element nodes (for tags), text nodes (for
content inside tags), and attribute nodes (for attributes like id or class).
4. Tree
Structure: The DOM is structured as a tree. The document is the root, and
everything else (elements, text, etc.) branches out from it.
For example, an HTML
document like this:
|
<!DOCTYPE
html> <html> <head> <title>My
Page</title> </head> <body> <h1>Welcome
to My Page</h1> <p>This
is a simple paragraph.</p> <button>Click
Me!</button> </body> </html> |
Is represented in the DOM
as a tree structure, where each element (such as <h1>, <p>, and
<button>) is a node that can be accessed and manipulated.
Why is the DOM important/Advantage of DOM
The DOM allows JavaScript
to dynamically change the content and structure of web pages after the page has
loaded. This is how interactive features like image sliders, form validation,
and dynamic content loading are achieved.
- JavaScript
can change all the HTML elements in the page
- JavaScript
can change all the HTML attributes in the page
- JavaScript
can change all the CSS styles in the page
- JavaScript
can remove existing HTML elements and attributes
- JavaScript
can add new HTML elements and attributes
- JavaScript
can react to all existing HTML events in the page
- JavaScript can create new HTML events in the page
The DOM Programming Interface
The HTML DOM can be
accessed with JavaScript (and with other programming languages).
In the DOM, all HTML
elements are defined as objects.
The programming interface
is the properties and methods of each object.
A property is
a value that you can get or set (like changing the content of an HTML element).
A method is
an action you can do (like add or deleting an HTML element).
Example
This example changes the
content (the innerHTML) of the <p> element
with id="demo":
|
<html> <body> |
In the example
above, getElementById is a method used to find id="demo
" to find the elememt, while innerHTML is
a property,which is useful for getting or replacing the content of
HTML elements.
The HTML DOM Document Object
The document object
represents your web page.
If you want to access any
element in an HTML page, you always start with accessing the document object.
Find or Select HTML Elements:
1. Selecting Elements in the DOM
Before manipulating an
HTML element, you need to select it. JavaScript provides multiple methods to
access DOM elements based on their attributes, tags, or other properties.
1.1. document.getElementById()
- Description:
Selects an element by its unique id attribute.
- Returns:
The first element with the specified id, or null if no match is found.
- Use
Case: Best for selecting a single element with a
known id.
Syntax:
const element =
document.getElementById('elementId');
Example:
|
<button
id="myButton">Click Me!</button> <script> const
button = document.getElementById('myButton');
console.log(button); // Outputs: <button
id="myButton">Click Me!</button> </script> |
1.2. document.querySelector()
- Description:
Selects the first element that matches a CSS selector. It
supports selectors for id, class, tag, or complex CSS rules.
- Returns:
The first matching element, or null if no match is found.
- Use
Case: Flexible and allows selecting elements using
any valid CSS selector.
Syntax:
const element =
document.querySelector('selector');
Example:
|
<p
class="message">Hello, World!</p> <script> const
paragraph = document.querySelector('.message');
console.log(paragraph); // Outputs: <p
class="message">Hello, World!</p> </script> |
Variations:
- document.querySelector('#id')
selects by id.
- document.querySelector('.class')
selects by class.
- document.querySelector('tag')
selects by tag name.
1.3. document.querySelectorAll()
- Description:
Selects all elements that match a CSS selector and
returns them as a NodeList (similar to an array but not
exactly the same).
- Returns:
A NodeList of matching elements.
- Use
Case: Useful for selecting multiple elements (e.g.,
all <p> tags or all elements with a certain class).
Syntax:
const elements =
document.querySelectorAll('selector');
Example:
|
<ul> <li
class="item">Item 1</li> <li
class="item">Item 2</li> <li
class="item">Item 3</li> </ul> <script> const
items = document.querySelectorAll('.item');
console.log(items); // Outputs: NodeList of all <li> elements
with class "item". </script> |
Key Note: You can loop through the NodeList using forEach:
items.forEach(item =>
console.log(item.textContent));
1.4. document.getElementsByClassName()
- Description:
Selects all elements with a specific class name and returns an HTMLCollection (live
collection that updates automatically if the DOM changes).
- Returns:
An HTMLCollection of matching elements.
- Use
Case: Quickly selects elements by class name.
Syntax:
const elements =
document.getElementsByClassName('className');
Example:
|
<div
class="box"></div> <div
class="box"></div> <script> const
boxes = document.getElementsByClassName('box');
console.log(boxes); // Outputs: HTMLCollection of all elements with
class "box". </script> |
1.5. document.getElementsByTagName()
- Description:
Selects all elements with a specific tag name and returns an HTMLCollection.
- Returns:
An HTMLCollection of matching elements.
- Use
Case: Useful for selecting all elements of a certain
type (e.g., all <p> or <div> tags).
Syntax:
const elements =
document.getElementsByTagName('tagName');
Example:
|
<p>First
paragraph</p> <p>Second
paragraph</p> <script> const
paragraphs = document.getElementsByTagName('p');
console.log(paragraphs); // Outputs: HTMLCollection of all <p>
elements. </script> |
1.6. document.forms
- Description:
Retrieves all <form> elements in the document as an HTMLCollection.
- Use
Case: Convenient for form manipulation.
Syntax:
const forms =
document.forms;
Example:
|
<form
id="loginForm">
<input type="text" name="username" /> </form> <script> const
forms = document.forms;
console.log(forms); // Outputs: HTMLCollection of all form elements. </script> |
1.7. document.images
- Description:
Retrieves all <img> elements in the document as an HTMLCollection.
- Use
Case: Quickly access all images on a page.
Syntax:
const images =
document.images;
1.8. document.links
- Description:
Retrieves all <a> elements with an href attribute as an HTMLCollection.
- Use
Case: Useful for working with navigation links.
Syntax:
const links =
document.links;
Comparison of Methods
|
Method |
Returns |
Selection Criteria |
Use Case |
|
getElementById() |
Single Element |
id |
Unique element
selection |
|
querySelector() |
Single Element |
CSS Selector |
Flexible, first match
only |
|
querySelectorAll() |
NodeList |
CSS Selector |
Flexible, multiple
matches |
|
getElementsByClassName() |
HTMLCollection |
Class Name |
Quick multiple class
selection |
|
getElementsByTagName() |
HTMLCollection |
Tag Name |
All elements of a
specific tag |
|
document.forms |
HTMLCollection |
<form> elements |
Accessing forms |
|
document.images |
HTMLCollection |
<img> elements |
Accessing images |
|
document.links |
HTMLCollection |
<a> with href
attribute |
Accessing hyperlinks |
These methods offer a
variety of ways to locate and work with elements, making them essential for
dynamic web development. Use them according to the specificity and performance
requirements of your task!
2. Changing Content and Style of Elements
Once an element is
selected, you can modify its content or style dynamically
using JavaScript.
2.1. Changing the Content
The content of an HTML
element can be changed using the properties innerHTML and textContent.
2.1.1. Using innerHTML
- Description:
Allows you to get or set the HTML content of an element.
It can include tags, so it is suitable for adding formatted content.
- Use
Case: Useful when you need to insert or modify HTML,
including child elements.
Syntax:
element.innerHTML = 'New
HTML Content';
Example:
|
<p
id="greeting">Hello</p> <script> //
Select the paragraph const
paragraph = document.getElementById('greeting');
// Change the HTML content
paragraph.innerHTML = '<strong>Hello, World!</strong>'; //
Adds bold text
console.log(paragraph.innerHTML); // Outputs: <strong>Hello,
World!</strong> </script> |
2.1.2. Using textContent
- Description:
Allows you to get or set the plain text content of an
element. It does not interpret HTML tags; instead, it treats them as plain
text.
- Use
Case: Useful when you want to ensure that the content
is plain text without any formatting.
Syntax:
element.textContent =
'New Plain Text Content';
Example:
|
<p
id="greeting">Hello</p> <script> //
Select the paragraph const
paragraph = document.getElementById('greeting');
// Change the plain text content
paragraph.textContent = '<strong>Hello,
JavaScript!</strong>'; // Displays the tags as plain text
console.log(paragraph.textContent); // Outputs: <strong>Hello,
JavaScript!</strong> </script> |
Differences Between innerHTML and textContent
|
Property |
Purpose |
Handles HTML Tags? |
Use Case |
|
innerHTML |
Get or set HTML content |
Yes |
For adding or modifying
formatted HTML |
|
textContent |
Get or set plain text
content only |
No |
For adding plain,
unformatted text |
2.2. Changing the Style
You can dynamically
change an element's appearance by modifying its style property.
This allows you to directly access and set CSS properties.
2.2.1. Modifying Individual CSS Properties
- Description:
Change the value of a specific CSS property using the style object.
- Syntax:
element.style.propertyName
= 'value';
Example:
|
<p
id="greeting">Hello</p> <script> const
paragraph = document.getElementById('greeting'); //
Change text color and font size
paragraph.style.color = 'blue';
paragraph.style.fontSize = '20px';
console.log(paragraph.style.color); // Outputs: blue </script> |
2.2.2. Adding Multiple Styles Using style.cssText
- Description:
Apply multiple CSS properties at once using a single string of CSS
declarations.
- Syntax:
element.style.cssText =
'property1: value1; property2: value2;';
Example:
|
<p
id="greeting">Hello</p> <script> const
paragraph = document.getElementById('greeting'); //
Apply multiple styles
paragraph.style.cssText = 'color: red; background-color: yellow; font-weight:
bold;'; </script> |
2.2.3. Adding or Removing Classes
Instead of modifying
styles directly, you can use CSS classes for styling and toggle them
dynamically.
Adding a Class:
element.classList.add('className');
Removing a Class:
element.classList.remove('className');
Toggling a Class:
element.classList.toggle('className');
Example:
|
<p
id="greeting" class="default">Hello</p> <style>
.highlight {
color: green;
font-size: 24px; } </style> <script> const
paragraph = document.getElementById('greeting');
// Add a class
paragraph.classList.add('highlight'); // Adds the "highlight"
class
console.log(paragraph.className); // Outputs: default highlight </script> |
Summary of Methods
|
Task |
Method |
Example |
|
Change HTML content |
element.innerHTML |
element.innerHTML =
'<strong>Hi!</strong>'; |
|
Change plain text |
element.textContent |
element.textContent =
'Plain Text'; |
|
Change single style |
element.style.propertyName |
element.style.color =
'red'; |
|
Add multiple styles |
element.style.cssText |
element.style.cssText =
'color: blue;'; |
|
Add a CSS class |
element.classList.add() |
element.classList.add('className'); |
|
Remove a CSS class |
element.classList.remove() |
element.classList.remove('className'); |
|
Toggle a CSS class |
element.classList.toggle() |
element.classList.toggle('className'); |
These methods allow you
to dynamically modify the content and appearance of web pages, enabling
interactive and responsive designs!
Properties
1. element.innerHTML
o Description:
Changes or retrieves the HTML content inside an element.
o Syntax:
element.innerHTML = 'New
HTML Content';
o Example:
document.getElementById('demo').innerHTML
= '<strong>Hello, World!</strong>';
2. element.attribute
o Description:
Changes the value of an attribute of an HTML element.
o Syntax:
element.id = 'newId';
element.src =
'newImage.jpg';
o Example:
document.getElementById('image').src
= 'newImage.jpg';
3. element.style.property
o Description:
Updates the CSS style of an HTML element.
o Syntax:
element.style.color =
'blue';
o Example:
document.getElementById('text').style.backgroundColor
= 'yellow';
Methods
1. element.setAttribute(attribute,
value)
o Description:
Sets or updates the value of a specified attribute for an HTML element.
o Syntax:
element.setAttribute('attribute',
'value');
o Example:
const link =
document.getElementById('myLink');
link.setAttribute('href',
'https://example.com');
Quick Reference Table
|
Property/Method |
Description |
Example |
|
element.innerHTML |
Changes the inner HTML
of an element |
element.innerHTML =
'<b>Bold Text</b>'; |
|
element.attribute |
Changes the value of an
attribute |
element.id = 'newId'; |
|
element.style.property |
Changes the CSS style
of an element |
element.style.color =
'red'; |
|
element.setAttribute() |
Sets or updates an
attribute value |
element.setAttribute('href',
'https://example'); |
Summary
These properties and
methods make it easy to:
- Update
the content of elements dynamically.
- Modify
styles for interactivity.
- Change
or add attributes programmatically.
2.2. Changing the Style
To change the style of an
element, you can access its style property. This allows you to modify CSS
styles directly through JavaScript.
Example:
- You
can modify any CSS property using JavaScript in this way (e.g., width,
height, border, font-size).
|
<button
id="colorButton">Change Color</button> <script> const
button = document.getElementById('colorButton'); button.style.backgroundColor
= 'blue'; // Changes the background color to blue button.style.color
= 'white'; // Changes the text color to white </script> |
Adding and Deleting Elements in JavaScript
JavaScript provides
powerful methods to add, remove, or replace HTML
elements dynamically in the DOM. These methods help developers create
interactive and dynamic web pages.
Key Methods for Manipulating HTML Elements
1. document.createElement(element)
- Description:
- Creates a new HTML element but does not add it to the DOM until explicitly
appended.
- Syntax:
const newElement =
document.createElement('tagName');
- Example:
|
const
newParagraph = document.createElement('p'); newParagraph.textContent
= 'This is a new paragraph!'; document.body.appendChild(newParagraph);
// Adds it to the body |
2. document.removeChild(element)
- Description:
Removes an existing child element from its parent node.
- Syntax:
parentElement.removeChild(childElement);
- Example:
|
const parent
= document.getElementById('container'); const child =
document.getElementById('item'); parent.removeChild(child);
// Removes the child element |
3. document.appendChild(element)
- Description:
- Appends an element as the last child of a parent element.
- Syntax:
parentElement.appendChild(newChild);
- Example:
|
const newItem
= document.createElement('li'); newItem.textContent
= 'New Item'; const list =
document.getElementById('myList'); list.appendChild(newItem);
// Adds the new list item |
4. document.replaceChild(new, old)
- Description:
Replaces an existing child element with a new one.
- Syntax:
parentElement.replaceChild(newElement,
oldElement);
- Example:
const newItem = document.createElement('li');newItem.textContent = 'Replaced Item';
const list = document.getElementById('myList');
const oldItem = document.getElementById('oldItem');
list.replaceChild(newItem, oldItem); // Replaces the old item with the new one
5. document.write(text)
- Description:
Writes HTML or text directly into the document. It is rarely used in
modern applications as it overwrites the current document if called after
the page has loaded.
- Syntax:
document.write('Hello,
World!');
- Example:
document.write('<h1>This
is written by document.write()</h1>');
Quick Reference Table
|
Method |
Description |
Example |
|
document.createElement() |
Creates a new HTML
element |
document.createElement('div'); |
|
document.removeChild() |
Removes an existing
child element |
parent.removeChild(child); |
|
document.appendChild() |
Adds a new child
element |
parent.appendChild(newElement); |
|
document.replaceChild() |
Replaces an old child
with a new one |
parent.replaceChild(newElement,
oldElement); |
|
document.write() |
Writes HTML or text to
the document |
document.write('<p>Hello,
World!</p>'); |
Practical Example
HTML:
|
<div
id="container"> <p
id="paragraph">This is a paragraph.</p> </div> |
JavaScript:
|
const
container = document.getElementById('container'); // Adding a
new element const newDiv
= document.createElement('div'); newDiv.textContent
= 'This is a new div!'; container.appendChild(newDiv); // Replacing
an element const
newParagraph = document.createElement('p'); newParagraph.textContent
= 'This is a replaced paragraph!'; container.replaceChild(newParagraph,
document.getElementById('paragraph')); // Removing
an element container.removeChild(newDiv); |
Best Practices
1. Use
document.createElement to dynamically generate elements rather than
hardcoding them in the HTML.
2. Avoid using
document.write in modern web development as it may overwrite existing content.
3. Use
appendChild or replaceChild for better DOM manipulation and dynamic updates.
These methods allow
developers to dynamically create, update, and manage elements on the webpage,
making it more interactive and functional.
3. Event Handling in JavaScript
JavaScript allows you to
respond to user actions (such as clicks, hovers, and keyboard input)
through event handling. You can attach events to
DOM elements to perform actions when a certain event occurs.
3.1. Adding Event Listeners
Event listeners are
functions that are called when a specific event occurs. To add an event
listener to an element, use the addEventListener() method.
Syntax:
element.addEventListener('event',
function() {
// Code to
execute when the event occurs
});
3.2. Handling Click Events
You can attach a click
event to an element to trigger a function when the element is clicked.
Example:
|
<button
id="clickMe">Click Me!</button> <script> const
button = document.getElementById('clickMe'); button.addEventListener('click',
function() { alert('Button
was clicked!'); }); </script> |
3.3. Handling Hover Events (Mouse Events)
To respond to hover
actions, you can use the mouseenter or mouseover events, and for mouseout or
leaving the element, you can use mouseleave.
Example:
|
<button
id="hoverButton">Hover over me!</button> <script> const
button = document.getElementById('hoverButton'); button.addEventListener('mouseenter',
function() { button.style.backgroundColor
= 'green'; // Change background color when mouse enters }); button.addEventListener('mouseleave',
function() { button.style.backgroundColor
= ''; // Reset the background color when mouse leaves }); </script> |
4. Practical Example:
Change Text and Style on Click
Let's combine these
concepts to create a simple example where clicking a button changes the text
and style of an element.
HTML:
|
<p
id="message">Click the button to change this text.</p> <button
id="changeTextButton">Change Text</button> |
JavaScript:
|
const button
= document.getElementById('changeTextButton'); const
paragraph = document.getElementById('message'); button.addEventListener('click',
function() { paragraph.innerHTML
= 'The text has been changed!'; paragraph.style.color
= 'blue'; paragraph.style.fontSize
= '20px'; }); |
In this example:
- When
the button is clicked, the text inside the <p> element changes to
"The text has been changed!".
- The
color of the text becomes blue, and its font size is increased to 20px.
5. Summary
- DOM allows
you to manipulate HTML elements using JavaScript.
- You
can select elements using getElementById() or querySelector().
- You
can change content using innerHTML or textContent.
- You
can modify styles using the style property.
- Event
handling allows you to respond to user
interactions such as clicks, hovers, and key presses.
- Event
listeners are attached to elements using addEventListener().

