Modifying Elements
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).
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).
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)
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")
Summary
- Use
innerHTMLto change HTML content. - Use
style.propertyto change inline styles. - Use
setAttributeor direct property access to change attributes. - Use
classListto manage CSS classes efficiently.
Quick Quiz
Which property is used to change the background color in JavaScript?
Enjoying these tutorials?