Jump to content

Featured Replies

Posted

You are reading Part 10 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 2]

Introduction

JavaScript provides powerful methods for modifying elements in the Document Object Model (DOM). By dynamically changing text content, attributes, classes, and styles, developers can create interactive and dynamic web applications.

Modifying elements dynamically in JavaScript is a key aspect of web interactivity. By changing text, attributes, classes, and styles, developers can create engaging user experiences. Mastering these techniques will enhance your ability to build responsive and interactive web applications.

1. Changing Text Content

Text inside an HTML element can be modified using textContent or innerHTML.

Using textContent

textContent changes only the text inside an element, preserving security by preventing script execution.

let heading = document.getElementById("title");
heading.textContent = "New Heading Text";

Using innerHTML

innerHTML allows adding HTML content but can pose security risks if dealing with user input.

let paragraph = document.getElementById("description");
paragraph.innerHTML = "<strong>Bold text added!</strong>";

2. Changing Attributes

Attributes like src, href, alt, and value can be dynamically modified using setAttribute() or direct property assignment.

Using setAttribute()

let image = document.getElementById("profilePic");
image.setAttribute("src", "newImage.jpg");
image.setAttribute("alt", "New profile picture");

Using Direct Property Assignment

document.getElementById("link").href = "https://newwebsite.com";

3. Modifying CSS Classes

Classes control the styling of elements. JavaScript allows adding, removing, and toggling classes dynamically.

Adding a Class

document.getElementById("box").classList.add("highlight");

Removing a Class

document.getElementById("box").classList.remove("hidden");

Toggling a Class

document.getElementById("menu").classList.toggle("open");

4. Modifying Inline Styles

CSS properties can be changed dynamically using the style property.

Changing a Single Style Property

document.getElementById("button").style.backgroundColor = "blue";

Applying Multiple Styles

let box = document.getElementById("box");
box.style.cssText = "width: 200px; height: 100px; background-color: yellow;";

You are reading Part 10 of the 39-part series: JavaScript Skill Progression: The Path from Beginner to Extreme. [Level 2]

  • Views 57
  • Created
  • Last Reply

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

Important Information

Terms of Use Privacy Policy Guidelines We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.