DOM Methods and Elements
The DOM (Document Object Model) is like a big map of the content on a webpage. It shows you all the things that make up the page, like buttons, text, images, and links. With JavaScript, you can use DOM Methods to change or interact with these parts of a webpage!
DOM (Document Object Model) methods and elements are essential components in web development, enabling developers to interact with and manipulate the content of an HTML document using JavaScript.
DOM Methods
DOM methods are functions provided by the DOM API that allow developers to perform various actions on the HTML document.DOM Methods are like magic spells that you can use in JavaScript to interact with your webpage. Each method does something special, like finding an element or changing it.
Methods | Description | Example |
---|---|---|
getElementById() | Finds and returns the element that has a specific ID. | const element = document.getElementById(‘example’); |
getElementsByClassName() | Finds and returns a list of all elements with a specific class name. | const elements = document.getElementsByClassName(‘example’); |
getElementsByTagName() | Finds and returns a list of elements with a specific HTML tag name. | const paragraphs = document.getElementsByTagName(‘p’); |
querySelector(): | Finds and returns the first element that matches a CSS selector. | const element = document.querySelector(‘#example .child-element’); |
querySelectorAll(): | Finds and returns all elements that match a CSS selector. | const elements = document.querySelectorAll(‘p.example’); |
DOM Elements
JavaScript is most commonly used to get or modify the content or value of the HTML elements on the page, as well as to apply some effects like show, hide, animations etc,DOM elements are the individual parts that make up a webpage, like buttons, paragraphs, images, and more. You can use JavaScript to change the content and style, or even add new elements to your webpage.
Methods | Description | Example |
---|---|---|
innerHTML | Finds and returns all elements that match a CSS selector. | document.getElementById(‘myDiv’).innerHTML = ‘Hello World!’; |
textContent | Gets or changes the text content inside an element (without any HTML tags). | document.getElementById(‘myDiv’).textContent = ‘Hello World!’; |
createElement(tagName) | Creates a new HTML element with the tag name you specify. | var newDiv = document.createElement(‘div’); |
createTextNode(text) | Creates a new text node with the text you provide. | var newText = document.createTextNode(‘Hello World!’); |
appendChild(newNode) | Adds a new child element to the end of an existing element. | document.getElementById(‘myDiv’).appendChild(newDiv); |
insertBefore(newNode, referenceNode): | Adds a new child element to the end of an existing element. | document.getElementById(‘myDiv’).insertBefore(newDiv, referenceDiv); |
Course Video:
Course Video English:
YouTube Reference :
1) JavaScript DOM Targeting Methods Tutorial in Hindi / Urdu
2) JavaScript DOM Get & Set Value Methods Tutorial in Hindi / Urdu
3) JavaScript DOM querySelector & querySelectorAll Tutorial in Hindi
4) JavaScript DOM Tutorial – Get Element By ID in English
5) JavaScript DOM Tutorial – Get Elements By Class or Tag in English
6) JavaScript DOM Tutorial – The Query Selector in English
Examples for Practice
1. Write a JS program in which Change the Background color of a Paragraph using the DOM element.
The task is to write a JavaScript program that changes the background color of a paragraph using the Document Object Model (DOM).
1. Access the Paragraph Element: Use JavaScript to select the paragraph element in the HTML document. You can do this by using document.getElementById(), document.querySelector(), or other similar methods to select the paragraph element by its ID or class.
2. Change the Background Color: Once you have selected the paragraph element, use the .style.backgroundColor property to change its background color. You can set this property to any valid CSS color value, such as “red”, “blue”, “#00ff00”, etc.
Here's an example program:
<body>
<p id=”myParagraph”>This is a paragraph.</p>
<script>
// Access the paragraph element using its ID
var paragraph = document.getElementById(“myParagraph”);
// Change the background color of the paragraph
paragraph.style.backgroundColor = “yellow”;
</script>
</body>
Output
2. Write a JS program to change the border style of the Paragraph by taking the border type from User (Dotted, Solid, Dashed) and changing the style using the DOM element.
The task is to write a JavaScript program that allows the user to input a border style (Dotted, Solid, Dashed) and changes the border style of a paragraph using the Document Object Model (DOM).
1. Get User Input: Use the prompt function to ask the user to enter a border style. Store the user input in a variable.
2. Access the Paragraph Element: Use JavaScript to select the paragraph element in the HTML document. You can do this by using document.getElementById(), document.querySelector(), or similar methods.
3. Change the Border Style: Once you have selected the paragraph element, use the .style.borderStyle property to change its border style. Set this property to the user input received from the prompt.
Here's an example program:
<body>
<p id=”myParagraph”>This is a paragraph.</p>
<script>
// Access the paragraph element using its ID
var paragraph = document.getElementById(“myParagraph”);
// Get user input for border style
var userBorderStyle = prompt(“Enter border style (Dotted, Solid, Dashed):”);
// Change the border style of the paragraph based on user input
paragraph.style.borderStyle = userBorderStyle;
</script>
</body>
Output
3. Using JS DOM elements change the color of the Paragraph as follows:- Paragraph 1:- Red Paragraph 2:- Blue Paragraph 3:- Green
The task is to write a JavaScript program that changes the color of three paragraphs with specific colors using the Document Object Model (DOM).
1. Access Paragraph Elements: Use JavaScript to select the three paragraph elements in the HTML document. You can do this by using document.getElementById(), document.querySelector(), or similar methods for each paragraph.
2. Change the Color: Once you have selected each paragraph element, use the .style.color property to change its text color. Set this property to the specific color for each paragraph.
Here's an example program:
<body>
<p id=”paragraph1″>Paragraph 1: This is red.</p>
<p id=”paragraph2″>Paragraph 2: This is blue.</p>
<p id=”paragraph3″>Paragraph 3: This is green.</p>
<script>
// Access paragraph elements using their IDs
var paragraph1 = document.getElementById(“paragraph1”);
var paragraph2 = document.getElementById(“paragraph2”);
var paragraph3 = document.getElementById(“paragraph3”);
// Change the color of each paragraph
paragraph1.style.color = “red”;
paragraph2.style.color = “blue”;
paragraph3.style.color = “green”;
</script>
</body>
Output
4. Write a JS program to change the color and Background of the Paragraph by taking the color and backgroundcolor name from the User and changing the style of the Paragraph using a DOM element.
The task is to write a JavaScript program that allows the user to input both the text color and background color and then changes the style of a paragraph using the Document Object Model (DOM).
1. Get User Input: Use the prompt function to ask the user to enter the text color and background color. Store these inputs in separate variables.
2. Access the Paragraph Element: Use JavaScript to select the paragraph element in the HTML document. You can do this by using document.getElementById(), document.querySelector(), or similar methods.
3. Change the Style: Once you have selected the paragraph element, use the .style.color property to change its text color, and the .style.backgroundColor property to change its background color. Set these properties to the user inputs received from the prompt.
Here's an example program:
<body>
<p id=”myParagraph”>This is a paragraph with dynamic style.</p>
<script>
// Access the paragraph element using its ID
var paragraph = document.getElementById(“myParagraph”);
// Get user input for text color and background color
var userTextColor = prompt(“Enter text color:”);
var userBackgroundColor = prompt(“Enter background color:”);
// Change the style of the paragraph based on user input
paragraph.style.color = userTextColor;
paragraph.style.backgroundColor = userBackgroundColor;
</script>
</body>
Output
5. Design a program that takes user input and uses a function to check if the answer is correct. If the answer is correct, display a success message with the class adding success; if it's wrong, display an error message with the class adding error. Must color change Classes : Success [Color: green), Error {color: red}
The task is to write a JavaScript program that takes user input, checks if the answer is correct using a function, and displays a success or error message with corresponding color changes.
1. Get User Input: – Use the prompt function to ask the user to enter their answer. Store the user input in a variable.
2. Define the Check Answer Function:
– Create a function called checkAnswer that takes the user’s input as a parameter.
– Inside this function, check if the answer is correct.
3. Display Success or Error Message:
– Use the Document Object Model (DOM) to display a message on the HTML document.
– If the answer is correct, add the class “success” with the text color set to green.
– If the answer is wrong, add the class “error” with the text color set to red.
Here's an example program:
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
.success {
color: green;
}
.error {
color: red;
}
</style>
</head>
<body>
<div id=”resultMessage”></div>
<script>
// Define the checkAnswer function
function checkAnswer(userInput) {
var correctAnswer = “9”;
// Convert both answers to uppercase for case-insensitive comparison
userInput = userInput.toUpperCase();
correctAnswer = correctAnswer.toUpperCase();
// Check if the answer is correct
if (userInput === correctAnswer) {
displayMessage(“Success! You got it right.”, “success”);
} else {
displayMessage(“Error! Wrong answer.”, “error”);
}
}
// Define a function to display the message with the specified class
function displayMessage(message, className) {
var resultMessage = document.getElementById(“resultMessage”);
resultMessage.textContent = message;
resultMessage.className = className;
}
// Wrap the code in a window load event
window.onload = function() {
// Get user input for the answer
var userAnswer = prompt(“5 + 4 = ?”);
// Call the checkAnswer function with user input
checkAnswer(userAnswer);
};
</script>
</body>
</html>
Output
6. Create a JavaScript program that includes an HTML element with a question and multiple-choice answers. Get the answer from the user by prompt. When the user selects the wrong answer, change the color of the text to red. If correct change the color Green. For Example: 2+2=? The answer is 6 The answer is 9 The answer is 4
The task is to write a JavaScript program that includes an HTML element with a question and multiple-choice answers. When the user selects the wrong answer, the text color should change to red, and if the answer is correct, the text color should change to green.
1. Get User Input: Use the prompt function to ask the user to select an answer from the multiple-choice options. Store the user input in a variable.
2. Check Answer and Change Text Color:
– Use JavaScript to check if the user’s answer is correct.
– If the answer is correct, change the text color to green.
– If the answer is wrong, change the text color to red.
Here's an example program:
<!DOCTYPE html>
<html lang=”en”>
<head>
<style>
body {
font-family: Arial, sans-serif;
}
.correct {
color: green;
}
.wrong {
color: red;
}
</style>
</head>
<body>
<div id=”question”>
<p>2 + 2 = ?</p>
<ul>
<li onclick=”checkAnswer(6)”>The answer is 6</li>
<li onclick=”checkAnswer(9)”>The answer is 9</li>
<li onclick=”checkAnswer(4)”>The answer is 4</li>
</ul>
</div>
<script>
// Function to check the user’s answer
function checkAnswer(userAnswer) {
var correctAnswer = 4;
// Check if the answer is correct
if (userAnswer === correctAnswer) {
displayResult(“Correct! Well done.”, “correct”);
} else {
displayResult(“Wrong answer. Try again.”, “wrong”);
}
}
// Function to display the result with the specified class
function displayResult(message, className) {
var resultElement = document.getElementById(“question”);
resultElement.innerHTML = ‘<p>’ + message + ‘</p>’;
resultElement.className = className;
}
</script>
</body>
</html>
Output
7. Change the Text Content of an Element using the DOM
Objective:
• Access the Element: Use JavaScript to select an element such as a paragraph, heading, or div by its ID or class.
• Modify the Text Content: Use the .textContent property to change the text inside the selected element dynamically.
Detailed Steps:
1. Use a method like getElementById() to access the element.
2. Then, update the text inside the element by assigning a new value to .textContent.
3. Implement the change through an event such as a button click.
Here's an example program:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Change Text Content</title>
</head>
<body>
<p id=”message”>This is the original message.</p>
<button onclick=”changeText()”>Change Text</button>
<script>
function changeText() {
// Access the paragraph element by its ID
const paragraph = document.getElementById(‘message’);
// Change the text content of the paragraph
paragraph.textContent = “This is the new text message!”;
}
</script>
</body>
</html>
Output
Before Click:
After Click:
8. Add a New List Item to an Existing List using the DOM
Objective:
• Select the List: Use JavaScript to select the <ul> or <ol> element from the DOM.
• Create a New List Item: Use document.createElement(‘li’) to create a new list item.
• Append the List Item: Use .appendChild() to add the new list item to the existing list.
Detailed Steps:
1. Select the list element (e.g., <ul>).
2. Create a new list item (<li>) using document.createElement().
3. Add the newly created list item to the existing list using .appendChild().
Here's an example program:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Add List Item</title>
</head>
<body>
<ul id=”myList”>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button onclick=”addListItem()”>Add New Item</button>
<script>
function addListItem() {
// Access the UL element by its ID
const list = document.getElementById(‘myList’);
// Create a new list item
const newItem = document.createElement(‘li’);
newItem.textContent = “New Item”;
// Append the new list item to the existing list
list.appendChild(newItem);
}
</script>
Output
Before Click:
After Click:
9. Remove an Element from the DOM
Objective:
• Select the Element: Use JavaScript to select an element by its ID or class.
• Remove the Element: Use the .remove() method to remove the selected element from the DOM.
Detailed Steps:
1. Select the element you want to remove (e.g., a paragraph or div).
2. Call the .remove() method on the selected element to delete it from the DOM.
3. Trigger the removal through a button click or another event.
Here's an example program:
<!DOCTYPE html>
<html lang=”en”>
<head>
<meta charset=”UTF-8″>
<meta name=”viewport” content=”width=device-width, initial-scale=1.0″>
<title>Add List Item</title>
</head>
<body>
<ul id=”myList”>
<li>Item 1</li>
<li>Item 2</li>
</ul>
<button onclick=”addListItem()”>Add New Item</button>
<script>
function addListItem() {
// Access the UL element by its ID
const list = document.getElementById(‘myList’);
// Create a new list item
const newItem = document.createElement(‘li’);
newItem.textContent = “New Item”;
// Append the new list item to the existing list
list.appendChild(newItem);
}
</script>
Output
Before Click:
After Click:
DOM methods are functions provided by the Document Object Model (DOM) API to interact with and manipulate the elements of an HTML document. Learn more in our JavaScript DOM methods and elements free course.
You can select elements using methods like:
- getElementById()
- getElementsByClassName()
- querySelector()
- querySelectorAll()
Explore these methods in our JS DOM methods with free video tutorial.
- querySelector: Selects the first matching element.
- querySelectorAll: Selects all matching elements and returns them as a NodeList.
Learn about their usage in the Free JavaScript DOM methods and elements tutorial.
Use the createElement() method to create new elements dynamically.
Example:
let newDiv = document.createElement(“div”);
document.body.appendChild(newDiv);
The appendChild() method adds a new node as the last child of a specified parent element. Learn how to use this method in our JavaScript DOM methods and elements free course.
Update content using the .innerHTML or .textContent property.
Example:
document.getElementById(“example”).innerHTML = “New Content”;
This is covered step-by-step in the JS DOM methods with free video tutorial.
- .innerHTML: Includes HTML tags within the content.
- .textContent: Sets or retrieves the text content only, ignoring HTML tags.
Find detailed explanations in the Free JavaScript DOM methods and elements tutorial.
Use the .remove() method or removeChild() method to delete elements.
Example:
document.getElementById(“example”).remove();
Learn this technique in the JS DOM methods and elements with free course.
The setAttribute() method allows you to set or update an attribute of an element.
Example:
document.getElementById(“myLink”).setAttribute(“href”, “https://example.com”);
This is explained in the JavaScript DOM methods and elements free course.
Use the addEventListener() method to attach event listeners to elements.
Example:
document.getElementById(“myButton”).addEventListener(“click”, function() {
alert(“Button clicked!”);
});
Watch this demonstrated in our JS DOM methods with free video tutorial.
You can learn about break and continue statements in our Learn JS break and continue with free video tutorial.
Yes, we offer a Free JavaScript break and continue course for beginners, where you can master these concepts step by step.