...

/

Modifying Content and Styles

Modifying Content and Styles

Learn to modify DOM elements by updating text, attributes, and styles.

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!';
Changing content of an H1 element

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'));
Modifying the target URL in an a tag

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 to modify inline CSS styles directly on an element.

const button = document.querySelector('button');
button.style.backgroundColor = 'blue';
button.style.color = 'white';
Dynamically adding colors to a button

The ...

Access this course and 1400+ top-rated courses and projects.