How do you change the content of an element with JavaScript?
There are three main ways to change an element, and picking the right one is most of the skill. The textContent property sets the text inside an element and always treats the value as plain text. The innerHTML property takes a string of markup and parses it as HTML. The classList property adds and removes class names, which is how you change the look of something without touching the styles directly.
// The DOM only exists in a browser, so check before you use it.
if (typeof document !== 'undefined') {
const card = document.querySelector('.card');
// Plain text is always safe.
card.textContent = 'Welcome back';
// Markup is parsed as HTML.
card.innerHTML = '<strong>Welcome back</strong>';
// Classes drive the styling.
card.classList.add('is-active');
card.classList.remove('is-loading');
console.log(card.classList.contains('is-active')); // true
// Attributes are for everything else.
card.setAttribute('aria-live', 'polite');
} else {
console.log('No DOM in this runtime. Open a browser console to try it.');
}The safety rule is the one to remember. If you set innerHTML with a string that contains something a user typed, the browser parses that text as markup. A value that contains a script tag then becomes a cross-site scripting hole. Setting textContent never has that problem, because the value can only ever be plain text. If you really need markup from a source you do not trust, clean it up first.
There is a speed difference as well. Assigning to innerHTML parses a whole new set of elements and throws away the old ones, so any event listeners on the old children are lost and any references you were holding are no longer valid. Setting textContent on a simple element does not have that cost.
For styling, the style property gives you access to one declaration at a time, and the cssText property replaces the whole block of declarations. The classList property is usually better than either of them, because it keeps the decision about what something looks like in the stylesheet, where it belongs.