Skip to content

Changing HTML & CSS

The HTML DOM allows JavaScript to change the content and style of HTML elements.

1. Changing HTML Content

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

document.getElementById("p1").innerHTML = "New text!";

innerText vs innerHTML

  • innerText: Gets/sets the text content (ignores HTML tags).
  • innerHTML: Gets/sets the HTML content (renders tags).

2. Changing Attributes

To change the value of an HTML attribute, use this syntax:

document.getElementById("myImage").src = "landscape.jpg";

3. Changing CSS Styles

To change the style of an HTML element, use this syntax:

document.getElementById("p2").style.color = "blue";
document.getElementById("p2").style.fontSize = "24px";

Hiding and Showing

// Hide
document.getElementById("p2").style.display = "none";

// Show
document.getElementById("p2").style.display = "block";

CSS Syntax

In CSS, property names use hyphens (background-color). In JavaScript, they use camelCase (backgroundColor).