Changing Content and Styles

Introduction
Changing content and styles is one of the most important features of JavaScript. It allows developers to update text, images, and design of a web page dynamically without reloading the page. This makes websites interactive and user friendly.

Understanding Content Manipulation
JavaScript can access and modify HTML elements using the Document Object Model commonly known as the DOM. Developers can change text, images, links, and other elements based on user actions or conditions.

Selecting Elements
To change content, you first need to select an HTML element. This can be done using methods like getElementById, querySelector, or getElementsByClassName.

Example

let heading = document.getElementById("title");
heading.textContent = "Welcome to JavaScript";

Changing Text Content
JavaScript allows you to update the text inside an element easily. The textContent property is commonly used for this purpose.

Example

document.getElementById("para").textContent = "Content updated successfully";

Changing HTML Content
You can also change the inner HTML of an element using innerHTML. This allows adding tags along with text.

Example

document.getElementById("box").innerHTML = "<b>Bold Text Added</b>";

Changing Styles
JavaScript can modify CSS styles directly. This helps in changing colors, sizes, layouts, and visibility.

Example

document.getElementById("box").style.color = "blue";
document.getElementById("box").style.backgroundColor = "lightgray";

Adding and Removing Classes
Instead of directly changing styles, you can use classList to add or remove CSS classes.

Example

let element = document.getElementById("box");
element.classList.add("active");
element.classList.remove("hidden");

Changing Attributes
JavaScript can also change attributes like image source or links.

Example

document.getElementById("image").src = "newimage.jpg";

Practical Use Cases
Updating content after a button click
Changing theme or dark mode
Displaying dynamic data from users
Creating animations and effects

Conclusion
Changing content and styles with JavaScript makes websites dynamic and interactive. It improves user experience by updating the page instantly without reload. Learning these techniques is essential for modern web development.

Home ยป Intermediate JavaScript > DOM Manipulation > Changing Content and Styles