JavaScript for Beginners: Mastering DOM Manipulation Step-by-Step

2.09K 0 0 0 0

📘 Chapter 3: Changing Text, HTML, and Attributes

🚀 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:

  • Editing element text (textContent, innerText)
  • Inserting or replacing HTML (innerHTML)
  • Changing attributes like src, href, alt, placeholder
  • Updating form inputs, images, and links
  • Best practices and security considerations

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:

  • Returns all text, including hidden elements
  • Faster and more consistent

🔍 innerText:

  • Returns visible text only
  • Affects layout reflow (slightly slower)

🧪 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:

  • Adding buttons, images, or nested tags
  • Displaying formatted API responses
  • Building reusable card or table layouts

🛠️ 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:

  • Change links
  • Switch image sources
  • Update input fields
  • Modify data-* attributes

🧾 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

  • How to update text using .textContent and .innerText
  • How to insert or replace HTML with .innerHTML and insertAdjacentHTML()
  • How to work with attributes using setAttribute(), getAttribute(), etc.
  • How to read and set form field values dynamically
  • How to apply this knowledge to create real-world interactions


In the next chapter, you’ll learn how to style elements, add/remove CSS classes, and manipulate layout directly with JavaScript.

Back

FAQs


1. What is the DOM in 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.

2. Is the DOM part of JavaScript?

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.

3. How do I select an element using JavaScript?

Use DOM methods like:

document.getElementById('id')

document.querySelector('.class')

document.querySelector('tag')

4. What’s the difference between innerHTML and textContent?

  • textContent only sets or gets plain text.
  • innerHTML lets you read or change the HTML structure, including tags.

5. How do I change the style of an element using JavaScript?

element.style.color = "red";

element.style.backgroundColor = "yellow";

Or better, toggle CSS classes:

element.classList.add('active');

element.classList.remove('hidden');

6. How do I add a new element to the page dynamically?

const div = document.createElement('div');

div.textContent = "Hello!";

document.body.appendChild(div);

7. How do I remove elements from the DOM?

element.remove(); // Modern way

// OR

element.parentNode.removeChild(element); // Older method

8. How do I handle user clicks or input with JavaScript?

const button = document.querySelector('button');

button.addEventListener('click', function() {

  alert('Button clicked!');

});

9. What are some beginner DOM projects I can try?

  • To-do list
  • Click counter
  • Image gallery with buttons
  • Live character counter for input fields
  • Simple calculator
  • Dark/light mode toggle