Modifying Elements

In JavaScript, you can modify existing HTML elements dynamically to change their content, attributes, and styles. This allows pages to update without reloading.

Common Ways to Modify Elements

  • Change content: Modify text or HTML inside an element.
  • Update attributes: Change element attributes like src, href, or class.
  • Modify styles: Adjust inline CSS styles dynamically.

1. Changing Content

Use textContent to change plain text or innerHTML to include HTML markup inside an element.

📌 Deep Dive: Changing Text and HTML Content

JAVASCRIPT
const para = document.querySelector('p');

// Change plain text
para.textContent = 'Hello, updated text!';

// Change with HTML
para.innerHTML = 'This is bold text!';
Output
Paragraph content updated accordingly

2. Updating Attributes

Modify element attributes using setAttribute() or direct property access.

📌 Deep Dive: Modifying Attributes

JAVASCRIPT
const img = document.querySelector('img');

// Using setAttribute
img.setAttribute('src', 'new-image.png');

// Using property
img.alt = 'Updated description';
Output
Image source and alt text updated

3. Changing Styles

Inline styles can be changed via the style property.

📌 Deep Dive: Modifying Inline Styles

JAVASCRIPT
const box = document.querySelector('.box');

// Change background color
box.style.backgroundColor = 'lightblue';

// Adjust width
box.style.width = '200px';
Output
Box style updated with new color and width
Illustration of modifying_elements
Illustration of modifying_elements

💡 Remember:

Use textContent for text only and innerHTML if you need to insert HTML markup. Be cautious with innerHTML to avoid security risks like XSS.

⚠️ Tip:

Directly setting styles via style only affects inline styles. For more complex style changes, consider toggling CSS classes.

Summary: Modifying Element Properties
ActionMethod / Property
Change text contentelement.textContent = 'text'
Change HTML contentelement.innerHTML = '<span>HTML</span>'
Update attributeelement.setAttribute('attr', 'value')
Update attribute (property)element.href = 'url'
Modify styleelement.style.property = 'value'