Modifying Elements
Modifying Elements
Section titled “Modifying Elements”Introduction
Section titled “Introduction”Once you have a reference to a DOM element, you can modify its content, attributes, classes, and styles.
Content
Section titled “Content”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)Attributes
Section titled “Attributes”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';Classes
Section titled “Classes”el.classList.add('active');el.classList.remove('hidden');el.classList.toggle('visible');el.classList.contains('active'); // true/false
// Replace one class with anotherel.classList.replace('old', 'new');Styles
Section titled “Styles”el.style.color = 'red';el.style.backgroundColor = '#f0f0f0';el.style.cssText = 'color: red; background: blue;';el.style.setProperty('--custom-var', 'value');Summary
Section titled “Summary”textContentfor safe text, avoidinnerHTMLwith user dataclassListAPI for class manipulationstyleproperty for inline styles- Use
setAttribute/getAttributefor data attributes