Skip to content
beginnerPhase 34 · DOM

Updating Elements

Modify element content, attributes, styles, and classes dynamically.

30m
0 problems
Topic Progress0%

Modifying Content

There are several ways to modify an element's content.

textContent vs innerHTML vs innerText

const element = document.querySelector('.content');

// textContent - gets/sets plain text
// - Fastest
// - Includes hidden elements
// - Doesn't parse HTML
element.textContent = 'Hello <b>World</b>'; // Shows HTML as text
console.log(element.textContent); // 'Hello <b>World</b>'

// innerHTML - gets/sets HTML
// - Slower (parses HTML)
// - XSS risk with user input
element.innerHTML = 'Hello <b>World</b>'; // Renders bold
console.log(element.innerHTML); // 'Hello <b>World</b>'

// innerText - gets/sets visible text
// - Slower (triggers layout reflow)
// - Only returns visible text
element.innerText = 'Hello World';
console.log(element.innerText); // 'Hello World'

Comparison Table

Method Parses HTML Includes Hidden Performance
textContent No Yes Fast
innerHTML Yes Yes Medium
innerText No No Slow

Practical Example

function updateStatus(message, type) {
  const status = document.getElementById('status');
  
  // Use textContent for safety
  status.textContent = message;
  
  // Use innerHTML for formatted content (if trusted)
  status.innerHTML = `<span class="${type}">${message}</span>`;
}

// For user input, always use textContent
function displayUserInput(text) {
  const display = document.getElementById('user-display');
  display.textContent = text; // Safe
}

Modifying Attributes

Elements have attributes like class, id, src, href, etc.

Setting Attributes

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

// setAttribute - works for any attribute
img.setAttribute('src', 'new-image.jpg');
img.setAttribute('alt', 'New image');
img.setAttribute('data-id', '123');

// Direct property - only for standard attributes
img.src = 'new-image.jpg';
img.alt = 'New image';

// Class (special handling)
img.className = 'new-class'; // Replaces all classes
img.classList.add('another'); // Add class
img.classList.remove('old'); // Remove class
img.classList.toggle('active'); // Toggle

Getting Attributes

const link = document.querySelector('a');

// getAttribute
const href = link.getAttribute('href');
const dataId = link.getAttribute('data-id');

// Direct property
const href2 = link.href; // May differ from getAttribute!

// Check if attribute exists
const hasTarget = link.hasAttribute('target');

Removing Attributes

// Remove attribute
link.removeAttribute('target');

// Remove class
link.classList.remove('disabled');

// Remove data attribute
link.removeAttribute('data-id');

Dataset (data-* attributes)

// HTML: <div data-user-id="123" data-role="admin">User</div>

const div = document.querySelector('[data-user-id]');

// Read
console.log(div.dataset.userId);  // '123' (camelCase)
console.log(div.dataset.role);    // 'admin'

// Write
div.dataset.status = 'active'; // Adds data-status="active"

// Remove
delete div.dataset.status;

// All data attributes
console.log(Object.entries(div.dataset));
// [['userId', '123'], ['role', 'admin']]

Modifying Styles

You can modify element styles through JavaScript.

Inline Styles

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

// Set single property
element.style.color = 'red';
element.style.backgroundColor = 'blue';
element.style.fontSize = '16px';

// Set multiple properties
element.style.cssText = 'color: red; background: blue; font-size: 16px;';

// Read style (only inline)
console.log(element.style.color); // 'red'
console.log(element.style.backgroundColor); // 'blue'

Computed Styles

// Get computed (final) styles
const computed = window.getComputedStyle(element);
console.log(computed.color);          // 'rgb(255, 0, 0)'
console.log(computed.fontSize);       // '16px'
console.log(computed.display);        // 'block'

// Check if element is visible
const isHidden = computed.display === 'none' || 
                 computed.visibility === 'hidden';

CSS Classes (Recommended)

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

// Add class
element.classList.add('active');
element.classList.add('highlight', 'selected');

// Remove class
element.classList.remove('active');

// Toggle class
element.classList.toggle('active');
element.classList.toggle('active', isActive); // Force state

// Check class
if (element.classList.contains('active')) {
  // Element has 'active' class
}

// Replace class
element.classList.replace('old-class', 'new-class');

CSS Custom Properties (Variables)

// Set CSS variable
element.style.setProperty('--primary-color', '#3498db');

// Read CSS variable
const primary = getComputedStyle(element)
  .getPropertyValue('--primary-color');

Best Practice: Use CSS Classes

// BAD: Inline styles
element.style.color = 'red';
element.style.fontWeight = 'bold';
element.style.padding = '10px';

// GOOD: Toggle classes
element.classList.add('error-state');

/* CSS */
.error-state {
  color: red;
  font-weight: bold;
  padding: 10px;
}

Practice Problems

0/3solved
Build Updating Elements Component

Create a reusable React component implementing Updating Elements. Include proper state management and accessibility.

Solution
// Production-ready component with:
// - Proper TypeScript types
// - Accessibility (ARIA)
// - Error boundaries
// - Loading states
// - Memoization where needed
Updating Elements Testing

Write unit and integration tests for Updating Elements using React Testing Library.

Solution
// Test coverage:
// 1. Rendering tests
// 2. Interaction tests
// 3. Edge case tests
// 4. Accessibility tests
Updating Elements Performance

Optimize Updating Elements for performance. Consider memoization, code splitting, and bundle size.

Solution
// Optimization techniques:
// 1. React.memo / useMemo / useCallback
// 2. Code splitting with lazy()
// 3. Virtual scrolling for lists
// 4. Image lazy loading
// 5. Bundle analysis

Quiz

1. What's the difference between textContent and innerHTML?

Question 1 options

2. How do you safely add a class to an element?

Question 2 options

3. How do you read the computed style of an element?

Question 3 options

4. What does element.dataset return?

Question 4 options

Flashcards

Question

textContent vs innerHTML?

Answer

textContent: plain text, no HTML parsing, safe. innerHTML: parses HTML, can render tags, XSS risk.

Question

How to add a class without removing others?

Answer

element.classList.add('classname') - preserves existing classes.

Question

How to read computed styles?

Answer

window.getComputedStyle(element).propertyName - returns the final computed value.

Question

What is element.dataset?

Answer

Access to data-* attributes. data-user-id becomes dataset.userId (camelCase conversion).

Question

What is Updating Elements?

Answer

Updating Elements is a key concept in frontend development.

Revision Notes

Key Takeaways

  • 1.textContent is safer than innerHTML for user content
  • 2.classList methods preserve existing classes
  • 3.getComputedStyle reads final computed styles
  • 4.Use CSS classes instead of inline styles
  • 5.Dataset provides clean access to data-* attributes

Interview Tips

  • Explain the difference between textContent, innerHTML, and innerText
  • Show how to use classList for dynamic styling
  • Demonstrate reading computed styles
  • Discuss best practices for modifying element content

Cheat Sheet

Updating Elements Cheat Sheet

Content

el.textContent = 'text';      // Plain text (safe)
el.innerHTML = '<b>html</b>';  // Parses HTML

Attributes

el.setAttribute('name', 'val');
el.getAttribute('name');
el.removeAttribute('name');
el.dataset.id = '123';

Styles

el.style.color = 'red';
el.classList.add('class');
el.classList.remove('class');
el.classList.toggle('class');
window.getComputedStyle(el).color;

Best Practices

  • Use textContent for user input
  • Use classes instead of inline styles
  • Use dataset for data attributes