Introductions
The Document Object Model (DOM) allows JavaScript to interact with HTML elements on a web page. With the DOM, you can change text, styles, attributes, classes, and even create or remove elements. In this chapter, you will practice the most important DOM concepts with simple examples, starting from selecting elements and gradually moving toward dynamic webpage manipulation. JavaScript DOM Practice questions with solutions help to understand the concepts.
Question 1: Select an HTML Element Using getElementById()
Problem
Select an HTML heading using its id and change its text using JavaScript.
Solution
<h1 id="heading">Old Heading</h1>
<script>
const heading = document.getElementById("heading");
heading.textContent = "Welcome to JavaScript";
</script>
Output
Welcome to JavaScript
Step-by-step Explanation
- The
<h1>element has anidcalledheading. document.getElementById("heading")finds that element.- The selected element is stored in
heading. textContentchanges the text.- The heading now displays
"Welcome to JavaScript".
Question 2: Change Text Using textContent
Problem
Create a paragraph and use JavaScript to change its text.
Solution
<p id="message">This is the old message.</p>
<script>
const message = document.getElementById("message");
message.textContent = "This is the new message.";
</script>
Output
This is the new message.
Step-by-step Explanation
- The paragraph has the ID
message. - JavaScript selects the paragraph.
textContentaccesses the text inside the element.- Assigning a new value replaces the old text.
Question 3: Change HTML Using innerHTML
Problem
Create a <div> and use JavaScript to insert a heading and paragraph inside it.
Solution
<div id="box"></div>
<script>
const box = document.getElementById("box");
box.innerHTML = `
<h2>Hello JavaScript</h2>
<p>Learning DOM is easy.</p>
`;
</script>
Output
Hello JavaScript
Learning DOM is easy.
Step-by-step Explanation
- The
<div>starts empty. - JavaScript selects the
<div>. innerHTMLallows you to insert HTML.- A heading and paragraph are added inside the
<div>. - The browser renders the new HTML.
Question 4: Change CSS Using JavaScript
Problem
Create a paragraph and use JavaScript to change its text color and font size.
Solution
<p id="text">JavaScript can change styles.</p>
<script>
const text = document.getElementById("text");
text.style.color = "blue";
text.style.fontSize = "24px";
</script>
Output
The paragraph appears blue with a font size of 24px.
Step-by-step Explanation
- JavaScript selects the paragraph using its ID.
style.colorchanges the text color.style.fontSizechanges the font size.- JavaScript can directly modify an element’s inline styles.
Question 5: Select Multiple Elements Using querySelectorAll()
Problem
Create three paragraphs with the same class and change the text color of all three paragraphs using querySelectorAll().
Solution
<p class="message">First paragraph</p>
<p class="message">Second paragraph</p>
<p class="message">Third paragraph</p>
<script>
const messages = document.querySelectorAll(".message");
messages.forEach(function(message) {
message.style.color = "green";
});
</script>
Output
All three paragraphs appear in green.
Step-by-step Explanation
- All three paragraphs have the class
message. querySelectorAll(".message")selects all matching elements.- The result is a collection of elements.
forEach()goes through each paragraph.- The text color of every paragraph is changed.
Question 6: Change an Element’s Attribute
Problem
Create an image and use JavaScript to change its src and alt attributes.
Solution
<img id="profileImage" src="old-image.jpg" alt="Old Image">
<script>
const image = document.getElementById("profileImage");
image.src = "new-image.jpg";
image.alt = "New Profile Image";
</script>
Output
The image source and alternative text are changed.
Step-by-step Explanation
- The image has the ID
profileImage. - JavaScript selects the image.
image.srcchanges the image source.image.altchanges the alternative text.- The browser uses the new attribute values.
You can also use:
image.setAttribute("src", "new-image.jpg");
Question 7: Add and Remove a CSS Class
Problem
Create a paragraph with a CSS class. Use JavaScript to add another class and then remove it.
Solution
<style>
.highlight {
background-color: yellow;
}
.large {
font-size: 25px;
}
</style>
<p id="message" class="highlight">JavaScript DOM Practice</p>
<script>
const message = document.getElementById("message");
message.classList.add("large");
message.classList.remove("highlight");
</script>
Output
The paragraph becomes larger and the yellow background is removed.
Step-by-step Explanation
- The paragraph initially has the
highlightclass. classList.add("large")adds thelargeclass.- The font size increases.
classList.remove("highlight")removes the yellow background.classListis useful for dynamically managing CSS classes.
Question 8: Create a New DOM Element
Problem
Create a new <li> element using JavaScript and add it to an existing list.
Solution
<ul id="skills">
<li>HTML</li>
<li>CSS</li>
</ul>
<script>
const skills = document.getElementById("skills");
const newSkill = document.createElement("li");
newSkill.textContent = "JavaScript";
skills.appendChild(newSkill);
</script>
Output
HTML
CSS
JavaScript
Step-by-step Explanation
- JavaScript selects the
<ul>. document.createElement("li")creates a new list item.textContentadds"JavaScript"to the new element.appendChild()adds the new<li>to the list.- The new item appears at the end of the list.
Question 9: Remove a DOM Element
Problem
Create a list with three items and use JavaScript to remove the second item.
Solution
<ul id="courses">
<li>HTML</li>
<li>CSS</li>
<li>JavaScript</li>
</ul>
<script>
const courses = document.getElementById("courses");
const secondCourse = courses.children[1];
secondCourse.remove();
</script>
Output
HTML
JavaScript
Step-by-step Explanation
- The
<ul>contains three list items. children[1]selects the second item because indexing starts from0.- The selected item is stored in
secondCourse. remove()removes that element from the page.- The CSS item is removed from the list.
Question 10: Create a Button That Changes Page Content
Problem
Create a button and a paragraph. When the button is clicked, change the paragraph text.
Solution
<p id="message">Click the button.</p>
<button id="changeButton">Change Message</button>
<script>
const button = document.getElementById("changeButton");
const message = document.getElementById("message");
button.addEventListener("click", function() {
message.textContent = "You clicked the button!";
});
</script>
Output
Before clicking:
Click the button.
[Change Message]
After clicking:
You clicked the button!
[Change Message]
Step-by-step Explanation
- JavaScript selects the button.
- JavaScript also selects the paragraph.
addEventListener()listens for aclickevent.- When the button is clicked, the callback function runs.
textContentchanges the paragraph.- The webpage updates without reloading.
Key Takeaways
- The DOM represents an HTML document as objects that JavaScript can access and modify.
getElementById()selects an element by its ID.querySelector()selects the first matching element.querySelectorAll()selects all matching elements.textContentchanges an element’s text.innerHTMLcan add or replace HTML content.- JavaScript can change CSS using the
styleproperty. classList.add()adds a CSS class.classList.remove()removes a CSS class.createElement()creates a new DOM element.appendChild()adds an element to the DOM.remove()removes an element.addEventListener()allows JavaScript to respond to user actions.
FAQs
1. What is the DOM in JavaScript?
DOM stands for Document Object Model. It represents the HTML page as objects that JavaScript can access and modify.
For example:
const heading = document.getElementById("heading");
JavaScript can then change that heading.
2. What is getElementById() used for?
getElementById() selects an HTML element using its unique id.
const heading = document.getElementById("heading");
3. What is the difference between textContent and innerHTML?
textContent changes or reads text.
element.textContent = "Hello";
innerHTML can insert HTML.
element.innerHTML = "<strong>Hello</strong>";
4. What is querySelector()?
querySelector() returns the first element that matches a CSS selector.
const heading = document.querySelector("h1");
You can also select a class:
const box = document.querySelector(".box");
5. What is querySelectorAll()?
querySelectorAll() selects all elements matching a CSS selector.
const paragraphs = document.querySelectorAll("p");
It is useful when you want to work with multiple elements.
6. How can JavaScript change CSS?
JavaScript can modify an element’s inline styles.
const heading = document.querySelector("h1");
heading.style.color = "red";
heading.style.fontSize = "30px";
7. How can JavaScript create a new HTML element?
Use document.createElement().
const paragraph = document.createElement("p");
paragraph.textContent = "New paragraph";
document.body.appendChild(paragraph);
This creates a new paragraph and adds it to the page.
Written by Shubhranshu Shekhar, who has trained 20000+ students in coding.
