Web Analytics

Modifying Elements

Beginner ~20 min read

Changing HTML Content

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

  • innerHTML: Gets or sets the HTML content (including tags).
  • innerText: Gets or sets the visible text content.
  • textContent: Gets or sets the text content (including hidden text).
HTML
CSS
JS

Changing CSS Styles

You can change the style of an HTML element using the style property.

element.style.property = "value";

Note: CSS properties with hyphens (like background-color) are written in camelCase in JavaScript (backgroundColor).

HTML
CSS
JS

Changing Attributes

You can change element attributes like src, href, alt, etc.

  • element.attribute = value (Direct property access)
  • element.setAttribute(name, value) (Method)
  • element.getAttribute(name) (Get value)
HTML
CSS
JS

Class Manipulation

The classList property is the best way to add, remove, or toggle CSS classes.

  • element.classList.add("class")
  • element.classList.remove("class")
  • element.classList.toggle("class")
  • element.classList.contains("class")
HTML
CSS
JS

Summary

  • Use innerHTML to change HTML content.
  • Use style.property to change inline styles.
  • Use setAttribute or direct property access to change attributes.
  • Use classList to manage CSS classes efficiently.

Quick Quiz

Which property is used to change the background color in JavaScript?

A
style.background-color
B
style.backgroundColor
C
style.bgColor
D
css.background