Changing what a page displays comes down to three moves. You replace the text inside an element, you write attributes on it, and you swap the CSS classes that decide how it looks. Handled carefully these operations are boring and predictable. Handled carelessly they produce the two classic bugs, which are a checkbox that will not tick and a user's name that is rendered as broken markup. This lesson works through each operation and the rule that keeps it safe.
The previous lesson in this module covered "Selecting DOM Elements: querySelector and Friends", and the next lesson in this module is about "Creating, Inserting and Removing Elements".
The previous lesson in this module explained how to select elements with querySelector, and the next lesson creates new elements and puts them into the page. Everything here starts from an element that you have already selected.
Should I write text with textContent or innerHTML?
textContent reads and writes plain text. Writing to it replaces every child of the element with one single text node, and the string is never treated as markup. Reading it gives you the visible text of the element and of everything inside it, with all of the tags stripped out. innerHTML does the opposite. It parses the string that you give it as HTML and builds real elements out of it.
That difference decides how you handle data that came from a person. If a display name contains angle brackets and an event-handler attribute, then innerHTML will happily turn it into a live element, and that is how markup injection bugs begin. textContent simply shows the characters, and nothing else happens. The rule that covers almost every case is simple. Values that a person supplied go in through textContent, and only markup that you wrote yourself goes in through innerHTML.
<form id="signup">
<label for="email">Email</label>
<input id="email" name="email" type="email" value="">
<label class="check">
<input id="newsletter" name="newsletter" type="checkbox"> Send me the newsletter
</label>
<button id="submit" type="submit">Create account</button>
</form>
<div id="status" class="badge badge--muted" data-state="idle">Idle</div>
const status = document.querySelector("#status");
// textContent writes plain text, so the angle brackets are just characters.
status.textContent = "Welcome, <b>Ada</b>";
console.log(status.textContent); // "Welcome, <b>Ada</b>"
console.log(status.querySelector("b")); // null - no element was created
// innerHTML parses the same string as markup.
status.innerHTML = "Welcome, <b>Ada</b>";
console.log(status.querySelector("b").textContent); // "Ada" - a real element now exists
How do I read, write and remove attributes?
Four methods cover everything that you will need. setAttribute(name, value) writes one. getAttribute(name) reads one back as a string. hasAttribute(name) answers whether it is there at all. And removeAttribute(name) deletes it. There is no getAttributeOrDefault, so you have to guard every read that might miss. getAttribute returns null for a missing attribute, and that is a different thing from an empty string.
const email = document.querySelector("#email");
email.setAttribute("placeholder", "[email protected]");
email.setAttribute("aria-required", "true");
console.log(email.getAttribute("placeholder")); // "[email protected]"
console.log(email.getAttribute("aria-required")); // "true"
console.log(email.getAttribute("data-role")); // null - missing attributes come back null
console.log(email.hasAttribute("required")); // false
email.removeAttribute("aria-required");
console.log(email.hasAttribute("aria-required")); // false
Attribute values are always strings. If you need a number, you convert it yourself with Number or with parseInt, because the DOM will not do that for you.
Why does the input still show the old value after you change the attribute?
Every element has two parallel representations. The attribute lives in the markup and describes the starting state of the element. The property lives on the element object and describes its current state. For most attributes the property reflects the attribute, so writing one updates the other and there is nothing to think about.
value is the exception, and it is worth understanding, because it explains a great many confused forum posts. The value attribute holds the default value, which is what the field starts with. The value property holds the current value, which is what is in the box right now. The moment somebody types, or you assign the property yourself, the two drift apart and the property wins. That is why the recommended way to fill in a field is the property, and the way to set a starting value in the markup is the attribute.
const email = document.querySelector("#email");
// The attribute is the default value that the field starts with.
email.setAttribute("value", "[email protected]");
console.log(email.value); // "[email protected]"
console.log(email.getAttribute("value")); // "[email protected]"
// The property is the live value. Once it changes, the attribute stays behind.
email.value = "[email protected]";
console.log(email.value); // "[email protected]"
console.log(email.getAttribute("value")); // "[email protected]"
The same split explains src on images and href on links. The attribute is the URL that is written in the markup, the property is the URL that is being fetched right now, and the two diverge when a page changes one of them without the other.
How do boolean attributes like disabled and checked behave?
Some attributes have no value at all. disabled, checked, required, hidden, and readonly are boolean. Their mere presence means true, and their absence means false. Writing disabled="false" does not enable the button, because the attribute is still there. That trips people up when they build attributes from a template.
For attributes like disabled and hidden, the property and the attribute mirror each other, and that makes the property the convenient way to work. Assigning false removes the attribute entirely, and assigning true adds it back with an empty value. Reading the attribute then gives you "" instead of the word "true", so check with hasAttribute when you need a yes-or-no answer. A checkbox behaves in a similar way from the point of view of your script. el.checked is the live state that you read and write, and el.checked = true ticks the box on screen, while the checked attribute in the markup is only the starting position.
const submit = document.querySelector("#submit");
submit.disabled = true;
console.log(submit.disabled); // true
console.log(submit.getAttribute("disabled")); // "" - present, but with an empty value
submit.disabled = false;
console.log(submit.disabled); // false
console.log(submit.hasAttribute("disabled")); // false - the attribute was removed
What is the safest way to change an element's CSS classes?
Setting el.className = "a b" replaces the entire class string, which means that adding one class silently removes all of the others. The classList object exists in order to avoid that. Its add, remove, contains, and replace methods each change exactly one class and leave the rest alone.
toggle deserves special mention. When you call it with one argument it flips the class, which makes code that runs twice behave differently the second time. When you call it with a second argument it sets the class to a definite value. toggle(name, true) guarantees that the class is present, and toggle(name, false) guarantees that it is gone. Either way it returns the resulting state, so you can branch on it.
const status = document.querySelector("#status");
status.classList.remove("badge--muted");
status.classList.add("badge--live");
console.log(status.className); // "badge badge--live"
console.log(status.classList.contains("badge--live")); // true
// The second argument makes toggle predictable instead of a coin flip.
status.classList.toggle("is-hidden", true);
console.log(status.className); // "badge badge--live is-hidden"
status.classList.toggle("is-hidden", false);
console.log(status.className); // "badge badge--live"
// replace swaps one class for another in a single step.
status.classList.replace("badge--live", "badge--error");
console.log(status.className); // "badge badge--error"
Two small habits keep this tidy. Prefer CSS classes for the visual state and keep the JavaScript limited to toggling named states such as is-loading or has-error, rather than writing inline styles. And never build a class string by joining it with a space and assigning it to className, unless you really do mean to replace every class on that element.
When should you hang small pieces of data on an element?
data-* attributes are a private channel between your markup and your script. They never affect how the page looks, which makes them ideal for carrying an id, a role, or a flag that a delegated click handler needs later. The dataset object is the script-side view of them. data-id becomes dataset.id, and hyphens turn into camelCase, so data-user-id becomes dataset.userId.
One caveat is worth keeping in mind, because every dataset value is a string. A data-count="3" attribute reads back as the string "3" and never as the number 3, so convert it where it matters.
const status = document.querySelector("#status");
status.dataset.state = "saved";
console.log(status.getAttribute("data-state")); // "saved"
console.log(status.dataset.state); // "saved"
status.dataset.userId = "u-4821";
console.log(status.dataset.userId); // "u-4821" - data-user-id becomes userId
console.log(typeof status.dataset.userId); // "string" - every data value is a string
The safe-mutation reference
el.textContent = valuereplaces the content of the element with plain text that is never parsed as markup.el.innerHTML = markupreplaces the content by parsing it as HTML, and you should use it only for markup that you trust.el.setAttribute(name, value),getAttribute,hasAttribute, andremoveAttributeare the full attribute toolkit.el.value,el.checked, andel.disabledread and write the live state of a form control.el.classList.add,remove,contains,toggle, andreplacechange CSS classes without disturbing the others.el.dataset.namereads and writesdata-nameattributes as camelCase properties.
Try it yourself: open a page that has a form, open the console, and select the email field with document.querySelector("input[type=email]"). Assign el.value = "[email protected]" and notice that the field fills in. Then run el.getAttribute("value") and see that the attribute never changed. Now try the reverse with el.setAttribute("value", "[email protected]") followed by el.value. Finally, add el.classList.add("is-trusted") and check el.className to watch the class list grow.