HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

JavaScript HTML DOM Content

The HTML DOM allows JavaScript to change the content and attributes of HTML elements. This is the core of creating dynamic web experiences.


Changing HTML Content

The easiest way to change the content of an HTML element is by using the innerHTML property.

document.getElementById("p1").innerHTML = "Hello World!";

innerHTML vs textContent

  • 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

Changing Attribute Values

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";

The setAttribute() Method

You can also use the setAttribute() method to change an attribute value.

element.setAttribute("class", "new-class-name");

Dynamic Date Modification

A common use case is displaying dynamic data like dates:

document.getElementById("dateHeader").innerHTML = "Today is " + Date();
Security Tip: When using 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.

Key Points to Remember

  • innerHTML can read and write HTML structure
  • textContent is safer for purely textual data
  • Attributes (src, href, id) are accessible as object properties
  • setAttribute() is a generic way to modify any attribute
  • Use JavaScript to swap images or update titles dynamically
  • Changes made via the DOM are volatile (lost on page refresh) unless saved to a database