JavaScript DOM Tutorial for Beginners
Welcome to the JavaScript DOM tutorial for beginners! This guide is designed to help you learn the Document Object Model (DOM) from scratch. We’ll cover the basics, provide coding examples, and include quiz questions to test your understanding. By the end of this tutorial, you’ll be able to manipulate web pages dynamically using JavaScript and the DOM. Let’s dive in!
Introduction to the DOM
What is the DOM?
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 provides a structured representation of the document (like a tree) and defines methods to access and manipulate the structure.
Why Learn the DOM?
- Dynamic Content: Manipulate web pages dynamically without reloading.
- Interactivity: Respond to user actions and events.
- Web Applications: Essential for building modern, interactive web applications.
Understanding the Document Object Model
The DOM represents an HTML document as a tree of nodes. Each node represents an HTML element, attribute, or text.
Example HTML:
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<h1 id=”main-heading”>Hello, World!</h1>
<p class=”text”>This is a sample paragraph.</p>
</body>
</html>
DOM Tree Representation:
- document
- head
- title
- body
- h1#main-heading
- p.text
- head
Accessing DOM Elements
JavaScript provides various methods to access elements in the DOM.
getElementById
Selects an element by its id attribute.
Syntax:
document.getElementById(‘id’);
Example:
let heading = document.getElementById(‘main-heading’);
console.log(heading.textContent); // Outputs: Hello, World!
getElementsByClassName
Selects elements by their class attribute. Returns a live HTMLCollection.
Syntax:
document.getElementsByClassName(‘className’);
Example:
let paragraphs = document.getElementsByClassName(‘text’);
console.log(paragraphs[0].textContent); // Outputs: This is a sample paragraph.
getElementsByTagName
Selects elements by their tag name. Returns an HTMLCollection.
Syntax:
document.getElementsByTagName(‘tagName’);
Example:
let headings = document.getElementsByTagName(‘h1’);
console.log(headings[0].textContent); // Outputs: Hello, World!
querySelector and querySelectorAll
Select elements using CSS selectors.
- querySelector: Returns the first matching element.
- querySelectorAll: Returns a static NodeList of all matching elements.
Syntax:
document.querySelector(‘selector’);
document.querySelectorAll(‘selector’);
Example:
let heading = document.querySelector(‘#main-heading’);
let paragraphs = document.querySelectorAll(‘.text’);
Quiz Question
Q1: Which method would you use to select an element with the id nav?
A. document.getElementById(‘nav’)
B. document.getElementsByClassName(‘nav’)
C. document.querySelector(‘.nav’)
D. document.getElement(‘nav’)
Answer: A. document.getElementById(‘nav’)
Manipulating DOM Elements
Once you’ve selected an element, you can manipulate it.
Changing Content
textContent: Sets or returns the text content of an element.
innerHTML: Sets or returns the HTML content inside an element.
Example:
let paragraph = document.querySelector(‘.text’);
paragraph.textContent = ‘Updated text content.’;
Modifying Attributes
Use the setAttribute and getAttribute methods.
Example:
let link = document.querySelector(‘a’);
link.setAttribute(‘href’, ‘https://www.example.com’);
let hrefValue = link.getAttribute(‘href’);
Styling Elements
You can change an element’s style using the style property.
Example:
let heading = document.getElementById(‘main-heading’);
heading.style.color = ‘blue’;
heading.style.fontSize = ’24px’;
Quiz Question
Q2: How do you change the text content of an element with the id message to “Hello, DOM!”?
A. document.getElementById(‘message’).value = ‘Hello, DOM!’;
B. document.getElementById(‘message’).textContent = ‘Hello, DOM!’;
C. document.getElementById(‘message’).innerHTML = ‘Hello, DOM!’;
D. Both B and C
Answer: D. Both B and C
Creating and Removing Elements
You can dynamically create and remove elements in the DOM.
createElement
Creates a new element node.
Syntax:
document.createElement(‘tagName’);
Example:
let newParagraph = document.createElement(‘p’);
newParagraph.textContent = ‘This is a new paragraph.’;
appendChild
Adds a node to the end of the list of children of a specified parent node.
Example:
let parent = document.querySelector(‘body’);
parent.appendChild(newParagraph);
removeChild
Removes a child node from the DOM.
Example:
let paragraph = document.querySelector(‘.text’);
parent.removeChild(paragraph);
Quiz Question
Q3: Which method would you use to create a new <div> element?
A. document.newElement(‘div’)
B. document.createElement(‘div’)
C. document.appendChild(‘div’)
D. document.createNode(‘div’)
Answer: B. document.createElement(‘div’)
Event Handling
Events are actions that occur when the user or browser manipulates a page.
Adding Event Listeners
Use the addEventListener method to listen for events.
Syntax:
element.addEventListener(‘event’, function);
Example:
let button = document.querySelector(‘button’);
button.addEventListener(‘click’, () => {
alert(‘Button clicked!’);
});
Common Events
- click: User clicks on an element.
- mouseover: User moves the mouse over an element.
- mouseout: User moves the mouse away from an element.
- keydown: User presses a key.
- submit: User submits a form.
Quiz Question
Q4: How do you attach a click event listener to a button with the id submitBtn?
A. submitBtn.onclick = function() { … };
B. document.getElementById(‘submitBtn’).addEventListener(‘click’, function() { … });
C. document.getElementById(‘submitBtn’).onClick = function() { … };
D. document.getElementById(‘submitBtn’).attachEvent(‘onclick’, function() { … });
Answer: B. document.getElementById(‘submitBtn’).addEventListener(‘click’, function() { … });
Traversing the DOM
Navigate between nodes in the DOM tree.
Parent, Child, and Sibling Nodes
- parentNode: Access the parent of a node.
- childNodes: Access the child nodes of an element (includes text nodes).
- children: Access child elements (excludes text nodes).
- firstChild and lastChild: Access the first and last child nodes.
- nextSibling and previousSibling: Navigate between siblings.
Example:
let listItem = document.querySelector(‘li’);
let parent = listItem.parentNode;
let nextItem = listItem.nextSibling;
Quiz Question
Q5: Which property would you use to access the parent of an element?
A. element.parentNode
B. element.childNode
C. element.nextSibling
D. element.previousSibling
Answer: A. element.parentNode
Practical Examples
To-Do List Application
Let’s build a simple to-do list that allows users to add and remove items.
HTML Structure:
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<h1>My To-Do List</h1>
<input type=”text” id=”item-input” placeholder=”Add a new item”>
<button id=”add-button”>Add</button>
<ul id=”todo-list”></ul>
<script src=”app.js”></script>
</body>
</html>
JavaScript (app.js):
let addButton = document.getElementById(‘add-button’);
let itemInput = document.getElementById(‘item-input’);
let todoList = document.getElementById(‘todo-list’);
addButton.addEventListener(‘click’, () => {
let itemText = itemInput.value;
if (itemText === ”) return;
let listItem = document.createElement(‘li’);
listItem.textContent = itemText;
let deleteButton = document.createElement(‘button’);
deleteButton.textContent = ‘Delete’;
listItem.appendChild(deleteButton);
todoList.appendChild(listItem);
itemInput.value = ”;
deleteButton.addEventListener(‘click’, () => {
todoList.removeChild(listItem);
});
});
Explanation:
- When the user clicks the “Add” button, a new list item is created and added to the list.
- A “Delete” button is appended to each list item to remove it from the list.
Quiz Questions
Q6: What does element.addEventListener(‘click’, function) do?
A. Adds a new element to the DOM
B. Removes an event listener
C. Attaches a function to execute when the element is clicked
D. Changes the style of the element
Answer: C. Attaches a function to execute when the element is clicked
Q7: Which property returns a collection of an element’s child nodes, including text and comment nodes?
A. element.childNodes
B. element.children
C. element.firstChild
D. element.parentNode
Answer: A. element.childNodes
Q8: How do you prevent a form from submitting when a button is clicked?
A. Return false in the event handler
B. Use event.preventDefault() in the event handler
C. Remove the action attribute from the form
D. Disable the submit button
Answer: B. Use event.preventDefault() in the event handler
Conclusion
Congratulations! You’ve learned the basics of the JavaScript DOM, including how to access and manipulate elements, handle events, and traverse the DOM tree. The DOM is a powerful tool for creating dynamic and interactive web pages. Keep practicing by building your own projects and experimenting with different methods and properties.
Welcome to the JavaScript DOM tutorial for beginners! This guide is designed to help you learn the Document Object Model (DOM) from scratch. We’ll cover the basics, provide coding examples, and include quiz questions to test your understanding. By the end of this tutorial, you’ll be able to manipulate web pages dynamically using JavaScript and the DOM. Let’s dive in!
Understanding the Document Object Model 3
querySelector and querySelectorAll 5
Creating and Removing Elements 7
Parent, Child, and Sibling Nodes 10
Introduction to the DOM
What is the DOM?
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 provides a structured representation of the document (like a tree) and defines methods to access and manipulate the structure.
Why Learn the DOM?
- Dynamic Content: Manipulate web pages dynamically without reloading.
- Interactivity: Respond to user actions and events.
- Web Applications: Essential for building modern, interactive web applications.
Understanding the Document Object Model
The DOM represents an HTML document as a tree of nodes. Each node represents an HTML element, attribute, or text.
Example HTML:
<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>
<h1 id=”main-heading”>Hello, World!</h1>
<p class=”text”>This is a sample paragraph.</p>
</body>
</html>
DOM Tree Representation:
- document
- head
- title
- body
- h1#main-heading
- p.text
- head
Accessing DOM Elements
JavaScript provides various methods to access elements in the DOM.
getElementById
Selects an element by its id attribute.
Syntax:
document.getElementById(‘id’);
Example:
let heading = document.getElementById(‘main-heading’);
console.log(heading.textContent); // Outputs: Hello, World!
getElementsByClassName
Selects elements by their class attribute. Returns a live HTMLCollection.
Syntax:
document.getElementsByClassName(‘className’);
Example:
let paragraphs = document.getElementsByClassName(‘text’);
console.log(paragraphs[0].textContent); // Outputs: This is a sample paragraph.
getElementsByTagName
Selects elements by their tag name. Returns an HTMLCollection.
Syntax:
document.getElementsByTagName(‘tagName’);
Example:
let headings = document.getElementsByTagName(‘h1’);
console.log(headings[0].textContent); // Outputs: Hello, World!
querySelector and querySelectorAll
Select elements using CSS selectors.
- querySelector: Returns the first matching element.
- querySelectorAll: Returns a static NodeList of all matching elements.
Syntax:
document.querySelector(‘selector’);
document.querySelectorAll(‘selector’);
Example:
let heading = document.querySelector(‘#main-heading’);
let paragraphs = document.querySelectorAll(‘.text’);
Quiz Question
Q1: Which method would you use to select an element with the id nav?
A. document.getElementById(‘nav’)
B. document.getElementsByClassName(‘nav’)
C. document.querySelector(‘.nav’)
D. document.getElement(‘nav’)
Answer: A. document.getElementById(‘nav’)
Manipulating DOM Elements
Once you’ve selected an element, you can manipulate it.
Changing Content
textContent: Sets or returns the text content of an element.
innerHTML: Sets or returns the HTML content inside an element.
Example:
let paragraph = document.querySelector(‘.text’);
paragraph.textContent = ‘Updated text content.’;
Modifying Attributes
Use the setAttribute and getAttribute methods.
Example:
let link = document.querySelector(‘a’);
link.setAttribute(‘href’, ‘https://www.example.com’);
let hrefValue = link.getAttribute(‘href’);
Styling Elements
You can change an element’s style using the style property.
Example:
let heading = document.getElementById(‘main-heading’);
heading.style.color = ‘blue’;
heading.style.fontSize = ’24px’;
Quiz Question
Q2: How do you change the text content of an element with the id message to “Hello, DOM!”?
A. document.getElementById(‘message’).value = ‘Hello, DOM!’;
B. document.getElementById(‘message’).textContent = ‘Hello, DOM!’;
C. document.getElementById(‘message’).innerHTML = ‘Hello, DOM!’;
D. Both B and C
Answer: D. Both B and C
Creating and Removing Elements
You can dynamically create and remove elements in the DOM.
createElement
Creates a new element node.
Syntax:
document.createElement(‘tagName’);
Example:
let newParagraph = document.createElement(‘p’);
newParagraph.textContent = ‘This is a new paragraph.’;
appendChild
Adds a node to the end of the list of children of a specified parent node.
Example:
let parent = document.querySelector(‘body’);
parent.appendChild(newParagraph);
removeChild
Removes a child node from the DOM.
Example:
let paragraph = document.querySelector(‘.text’);
parent.removeChild(paragraph);
Quiz Question
Q3: Which method would you use to create a new <div> element?
A. document.newElement(‘div’)
B. document.createElement(‘div’)
C. document.appendChild(‘div’)
D. document.createNode(‘div’)
Answer: B. document.createElement(‘div’)
Event Handling
Events are actions that occur when the user or browser manipulates a page.
Adding Event Listeners
Use the addEventListener method to listen for events.
Syntax:
element.addEventListener(‘event’, function);
Example:
let button = document.querySelector(‘button’);
button.addEventListener(‘click’, () => {
alert(‘Button clicked!’);
});
Common Events
- click: User clicks on an element.
- mouseover: User moves the mouse over an element.
- mouseout: User moves the mouse away from an element.
- keydown: User presses a key.
- submit: User submits a form.
Quiz Question
Q4: How do you attach a click event listener to a button with the id submitBtn?
A. submitBtn.onclick = function() { … };
B. document.getElementById(‘submitBtn’).addEventListener(‘click’, function() { … });
C. document.getElementById(‘submitBtn’).onClick = function() { … };
D. document.getElementById(‘submitBtn’).attachEvent(‘onclick’, function() { … });
Answer: B. document.getElementById(‘submitBtn’).addEventListener(‘click’, function() { … });
Traversing the DOM
Navigate between nodes in the DOM tree.
Parent, Child, and Sibling Nodes
- parentNode: Access the parent of a node.
- childNodes: Access the child nodes of an element (includes text nodes).
- children: Access child elements (excludes text nodes).
- firstChild and lastChild: Access the first and last child nodes.
- nextSibling and previousSibling: Navigate between siblings.
Example:
let listItem = document.querySelector(‘li’);
let parent = listItem.parentNode;
let nextItem = listItem.nextSibling;
Quiz Question
Q5: Which property would you use to access the parent of an element?
A. element.parentNode
B. element.childNode
C. element.nextSibling
D. element.previousSibling
Answer: A. element.parentNode
Practical Examples
To-Do List Application
Let’s build a simple to-do list that allows users to add and remove items.
HTML Structure:
<!DOCTYPE html>
<html>
<head>
<title>To-Do List</title>
</head>
<body>
<h1>My To-Do List</h1>
<input type=”text” id=”item-input” placeholder=”Add a new item”>
<button id=”add-button”>Add</button>
<ul id=”todo-list”></ul>
<script src=”app.js”></script>
</body>
</html>
JavaScript (app.js):
let addButton = document.getElementById(‘add-button’);
let itemInput = document.getElementById(‘item-input’);
let todoList = document.getElementById(‘todo-list’);
addButton.addEventListener(‘click’, () => {
let itemText = itemInput.value;
if (itemText === ”) return;
let listItem = document.createElement(‘li’);
listItem.textContent = itemText;
let deleteButton = document.createElement(‘button’);
deleteButton.textContent = ‘Delete’;
listItem.appendChild(deleteButton);
todoList.appendChild(listItem);
itemInput.value = ”;
deleteButton.addEventListener(‘click’, () => {
todoList.removeChild(listItem);
});
});
Explanation:
- When the user clicks the “Add” button, a new list item is created and added to the list.
- A “Delete” button is appended to each list item to remove it from the list.
Quiz Questions
Q6: What does element.addEventListener(‘click’, function) do?
A. Adds a new element to the DOM
B. Removes an event listener
C. Attaches a function to execute when the element is clicked
D. Changes the style of the element
Answer: C. Attaches a function to execute when the element is clicked
Q7: Which property returns a collection of an element’s child nodes, including text and comment nodes?
A. element.childNodes
B. element.children
C. element.firstChild
D. element.parentNode
Answer: A. element.childNodes
Q8: How do you prevent a form from submitting when a button is clicked?
A. Return false in the event handler
B. Use event.preventDefault() in the event handler
C. Remove the action attribute from the form
D. Disable the submit button
Answer: B. Use event.preventDefault() in the event handler
Conclusion
Congratulations! You’ve learned the basics of the JavaScript DOM, including how to access and manipulate elements, handle events, and traverse the DOM tree. The DOM is a powerful tool for creating dynamic and interactive web pages. Keep practicing by building your own projects and experimenting with different methods and properties.