The HTML DOM allows JavaScript to change the content and attributes of HTML elements. This is the core of creating dynamic web experiences.
The easiest way to change the content of an HTML element is by using the
innerHTML property.
document.getElementById("p1").innerHTML = "Hello World!";
innerHTML: Returns and sets the content including HTML
tags.textContent: Returns and sets only the plain text content,
ignoring HTML tags.element.innerHTML = "Bold Text"; // Works
element.textContent = "Bold Text"; // Displays the tags as literal text
You can change the value of any HTML attribute by accessing it as a property of the element object.
// Change an image source
document.getElementById("myImage").src = "landscape.jpg";
// Change a link's href
document.getElementById("myLink").href = "https://www.google.com";
You can also use the setAttribute() method to change an
attribute value.
element.setAttribute("class", "new-class-name");
A common use case is displaying dynamic data like dates:
document.getElementById("dateHeader").innerHTML = "Today is " + Date();
innerHTML to display user-generated
content, be careful of Cross-Site Scripting (XSS) attacks. If you only need to
show text, use textContent for better security.
innerHTML can read and write HTML structuretextContent is safer for purely textual datasetAttribute() is a generic way to modify any attribute