About Lesson
Changing Content and Styles
Once you’ve selected elements, you can modify their content and styles dynamically using JavaScript.
1. Changing Text Content (textContent)
textContent changes the textual content of an element. It is the simplest and safest way to update the content, as it sets plain text without parsing HTML.
Example:
JavaScript
let heading = document.getElementById("main-title");
heading.textContent = "Hello, World!";
2. Changing HTML Content (innerHTML)
innerHTML changes the entire HTML content inside an element. Be cautious when using this property, as it can introduce security risks like cross-site scripting (XSS) if not handled properly.
Example:
JavaScript
let container = document.querySelector(".container");
container.innerHTML = "<h2>New Heading</h2><p>Updated content.</p>";
3. Changing Styles
The style property allows you to directly modify an element’s CSS styles.
Example:
JavaScript
let heading = document.querySelector("#main-title");
heading.style.color = "red";
heading.style.fontSize = "30px";
heading.style.backgroundColor = "lightgray";
However, using style directly like this applies inline styles. A more scalable approach is to toggle class names using classList.
4. Toggling Class Names
Example:
JavaScript
let heading = document.querySelector("#main-title");
heading.classList.add("highlight");
heading.classList.remove("highlight");
heading.classList.toggle("highlight"); // Toggles the class