Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Take A QuizChallenge yourself and boost your learning! Start the quiz now to earn credits.
Take A QuizUnlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
Take A Quiz
🚀 Introduction: Making
Webpages Dynamic with JavaScript
Now that you can confidently select elements in the DOM, the
next step is learning how to change what users see and interact with —
this includes updating text, injecting HTML, modifying attributes, and handling
content dynamically.
This chapter focuses on:
Let’s transform static HTML into dynamic, interactive
experiences.
🧠 Core Concepts Overview
Task |
Method/Property |
Use Case |
Change text |
.textContent,
.innerText |
Headings, labels,
paragraphs |
Inject HTML |
.innerHTML |
Adding spans,
images, or tags |
Modify attributes |
.setAttribute(),
.getAttribute() |
Links, image sources,
data attributes |
Read/update input values |
.value |
Forms and
user input |
📌 1. Changing Text:
textContent vs innerText
🧾 Example HTML:
html
<h2
id="title">Welcome to my site</h2>
✅ JavaScript:
javascript
const
title = document.getElementById('title');
title.textContent
= 'Thanks for visiting!';
🔍 textContent:
🔍 innerText:
🧪 Compare Behavior:
Property |
Includes hidden
text? |
Affects layout? |
textContent |
✅ Yes |
❌ No |
innerText |
❌
No |
✅
Yes |
🎨 2. Injecting HTML:
innerHTML
innerHTML allows you to replace or add HTML markup
inside an element.
🔹 Example:
html
<div
id="box"></div>
javascript
const
box = document.getElementById('box');
box.innerHTML
= "<h3>New Heading</h3><p>This content was added with
JavaScript!</p>";
⚠️ Be cautious using innerHTML
with user input — it can expose your site to XSS attacks.
🔧 Use Cases for
innerHTML:
🛠️ 3. Safely Appending
Content with insertAdjacentHTML()
Instead of replacing all content, you can use:
javascript
element.insertAdjacentHTML(position,
htmlString);
Position |
Inserts relative
to element |
"beforebegin" |
Before the element
itself |
"afterbegin" |
Just inside
the element, before its first child |
"beforeend" |
Just inside the
element, after its last child |
"afterend" |
After the
element itself |
✅ Example:
javascript
box.insertAdjacentHTML('beforeend',
'<p>Another paragraph!</p>');
🌐 4. Changing Attributes
with JavaScript
You can dynamically:
🧾 Common Methods:
Method |
Description |
getAttribute(attr) |
Reads the value of an
attribute |
setAttribute(attr, val) |
Sets or
changes an attribute |
removeAttribute(attr) |
Removes an attribute |
hasAttribute(attr) |
Returns true
if the element has the attribute |
🎯 Example 1: Updating an
Image Source
html
<img
id="banner" src="default.jpg" alt="Banner
Image">
javascript
const
banner = document.getElementById('banner');
banner.setAttribute('src',
'new-banner.jpg');
banner.setAttribute('alt',
'Updated image banner');
🎯 Example 2: Dynamic Link
Update
html
<a
id="profileLink" href="#">Visit Profile</a>
javascript
const
link = document.getElementById('profileLink');
link.setAttribute('href',
'https://linkedin.com/in/yourname');
🧾 5. Reading and Setting
Form Input Values
JavaScript can read and update form inputs easily using the
.value property.
html
<input
type="text" id="username" placeholder="Enter
name" />
🔹 Read Value:
javascript
const
nameInput = document.getElementById('username');
console.log(nameInput.value);
// logs user input
🔹 Set Value:
javascript
nameInput.value
= "John Doe";
💡 Also works with
<textarea> and <select> fields.
💡 Bonus: Accessing
dataset for Custom Data
HTML5 introduced data-* attributes to store custom values.
html
<button
id="deleteBtn" data-id="789">Delete</button>
javascript
const
btn = document.getElementById('deleteBtn');
console.log(btn.dataset.id);
// 789
✅ Very useful for working with
dynamic content and APIs.
🧪 Real-World Use Case:
Building a Notification Message
🔸 HTML:
html
<div
id="notification" class="hidden"></div>
🔸 JavaScript:
javascript
const
note = document.getElementById('notification');
function
showMessage(message) {
note.textContent = message;
note.classList.remove('hidden');
}
🔔 This is the basic
structure of alert boxes, toast messages, etc.
🧱 Comparing DOM
Manipulation Methods
Task |
Best Practice |
Change plain text |
Use .textContent |
Inject tags |
Use
.innerHTML (with caution) |
Add content without
replacing |
Use
.insertAdjacentHTML() |
Read/update form fields |
Use .value |
Modify attributes |
Use .setAttribute() or
direct access |
🧠 Common Mistakes and
Fixes
Problem |
Cause |
Fix |
undefined value |
Element not selected
properly |
Check selector and
timing |
HTML appears as text |
Used
textContent instead of innerHTML |
Switch
methods |
Attribute not updating |
Used wrong name (e.g.,
"className" instead of "class") |
Use setAttribute() or
correct property |
🧾 Summary Table
Operation |
Method |
Example |
Change text |
.textContent |
element.textContent =
"New Text"; |
Insert HTML |
.innerHTML |
element.innerHTML
= "<b>Bold</b>"; |
Update attribute |
.setAttribute() |
element.setAttribute("src",
"img.jpg") |
Read form input |
.value |
input.value |
Add HTML safely |
.insertAdjacentHTML() |
element.insertAdjacentHTML("beforeend",
"<p>Hi</p>") |
📍 Summary: What You’ve
Learned
In the next chapter, you’ll learn how to style elements,
add/remove CSS classes, and manipulate layout directly with JavaScript.
A: The DOM (Document Object Model) is a
tree-like structure that represents your web page. JavaScript can access and
modify this structure to change elements, styles, content, and more—dynamically
and in real-time.
A: Not exactly. The DOM is a Web API provided by
the browser, but JavaScript interacts with it using built-in methods like
getElementById, querySelector, and addEventListener.
Use DOM methods like:
document.getElementById('id')
document.querySelector('.class')
document.querySelector('tag')
element.style.color
= "red";
element.style.backgroundColor
= "yellow";
Or better, toggle CSS classes:
element.classList.add('active');
element.classList.remove('hidden');
const
div = document.createElement('div');
div.textContent = "Hello!";
document.body.appendChild(div);
element.remove();
// Modern way
// OR
element.parentNode.removeChild(element);
// Older method
const
button = document.querySelector('button');
button.addEventListener('click',
function() {
alert('Button clicked!');
});
Please log in to access this content. You will be redirected to the login page shortly.
LoginReady to take your education and career to the next level? Register today and join our growing community of learners and professionals.
Comments(0)