Modifying DOM Elements

Once you have accessed an element, you can modify its content, attributes, or styles.

Changing Text Content

You can change the text content of an element using the textContent property.

element.textContent = "New Text Content";

Changing HTML Content

To modify the HTML content of an element, use the innerHTML property.

element.innerHTML = "<strong>New</strong> HTML Content";

Modifying Attributes

You can change element attributes using the setAttribute method.

element.setAttribute("src", "new-image.jpg");

Modifying Styles

To change the styles of an element, access its style property and modify specific style properties.

element.style.backgroundColor = "red";
element.style.color = "white";

Continuing the tribute page example, let’s try to customize the HTML elements.

Task

  1. Change the text content of the heading to About Infosys Limited and change the text color to blue.
  2. Set the src attribute of the image element to https://www.learnwebstack.com/wp-content/uploads/2023/10/infosys-founders.jpg and set the width to 350px.
  3. Change the font style italic to the second paragraph.
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT