Modifying Content and Styles
Explore how to modify web page content and styles dynamically using DOM properties such as textContent, innerHTML, and style. Learn to manage attributes and toggle classes efficiently with classList methods for interactive web development.
Modifying elements in the DOM allows us to dynamically update a web page’s content and behavior. In this lesson, we'll explore what we can do with DOM and how it helps us make our websites more interactive.
Changing text content
We can use the textContent property to update or retrieve the textual content of an element.
const heading = document.querySelector('h1');heading.textContent = 'Welcome to JavaScript!';
The above example updates the text inside an <h1> element to 'Welcome to JavaScript!'.
Modifying attributes
The setAttribute() and getAttribute() methods let you manipulate an element’s attributes.
const link = document.querySelector('a');link.setAttribute('href', 'https://example.com');console.log(link.getAttribute('href'));
This code sets the href attribute of an anchor element to a new URL and logs the updated value.
Updating styles dynamically
The style property allows you ...