Skip to content

Modifying Elements

Once you have a reference to a DOM element, you can modify its content, attributes, classes, and styles.

const el = document.querySelector('.target');
el.textContent = 'New text'; // Plain text (safe — no XSS risk)
el.innerHTML = '<b>Bold text</b>'; // HTML (XSS risk with user data!)
el.innerText = 'Visible text'; // Respects CSS visibility (slower)
el.setAttribute('disabled', '');
el.getAttribute('disabled'); // ''
el.removeAttribute('disabled');
el.hasAttribute('disabled'); // false
// Boolean properties (preferred for known properties)
el.disabled = true;
el.id = 'new-id';
el.classList.add('active');
el.classList.remove('hidden');
el.classList.toggle('visible');
el.classList.contains('active'); // true/false
// Replace one class with another
el.classList.replace('old', 'new');
el.style.color = 'red';
el.style.backgroundColor = '#f0f0f0';
el.style.cssText = 'color: red; background: blue;';
el.style.setProperty('--custom-var', 'value');
  • textContent for safe text, avoid innerHTML with user data
  • classList API for class manipulation
  • style property for inline styles
  • Use setAttribute/getAttribute for data attributes