JavaScript DOM Manipulation - Changing Element Content


JavaScript allows you to manipulate the content of HTML elements in real-time. In this guide, we'll explore how to change the content of HTML elements using JavaScript and provide examples to illustrate the process.


Getting Elements


Before changing an element's content, you need to select the element using JavaScript. You can do this using various methods, such as getElementById, querySelector, or getElementsByClassName:


<!-- HTML -->
<div id="content">Initial Content</div>
// JavaScript
const elementById = document.getElementById("content");
const elementQuery = document.querySelector("#content");
const elementsByClass = document.getElementsByClassName("classname");

Changing Text Content


You can change the text content of an element using the textContent property:


const element = document.getElementById("content");
element.textContent = "New Text Content";

Changing HTML Content


To change the HTML content of an element, use the innerHTML property:


const element = document.getElementById("content");
element.innerHTML = "<em>New</em> HTML Content";

Creating New Elements


You can create new elements and append them to the document using the createElement and appendChild methods:


const newElement = document.createElement("p");
newElement.textContent = "This is a new paragraph.";
document.body.appendChild(newElement);

Modifying Element Attributes


You can modify element attributes like src for images or href for links:


const imageElement = document.getElementById("image");
imageElement.src = "new-image.jpg";
const linkElement = document.getElementById("link");
linkElement.href = "https://example.com";

Conclusion


JavaScript DOM manipulation empowers you to dynamically change the content of HTML elements. This enables you to build interactive and responsive web applications by updating the user interface in real-time based on user actions and data.


Happy coding!