Changing content and attributes
An element has four things a program changes: its text, its markup, its classes and its attributes. The first two look alike and behave very differently, because one of them treats a string as text and the other one parses it as HTML. The last two are how a page carries state: a class moves an element between the rules of a stylesheet, and a data attribute keeps a value the page can read later.
The four programs of this lesson run on one small card and print the result of each write, including the serialised markup of the element after a write and the error that a class with a space in it produces. The page is built by jsdom as the first lesson of this part showed, and the serialised HTML in the output comes from that same version of the library.
Text, and text that looks like markup
textContent reads every text node inside an element and joins them, and a write to it removes the children and puts one text node in their place. The string is never parsed, so a paragraph that receives <b>bold</b> shows those characters and keeps zero child elements. This is the property for user text, and it is also the one to print when a lesson has to show what a page says.
The program reads the text of the card, writes a string with tags in it to the paragraph, and prints both the text and the serialised element.
The file text.js:
const { JSDOM } = require('jsdom');
const html = '<!doctype html><body><div id="box" class="card"><p class="lead">Hello <b>world</b></p></div></body>';
const dom = new JSDOM(html, { url: 'http://localhost/' });
const { document } = dom.window;
const box = document.querySelector('#box');
const lead = box.querySelector('.lead');
console.log('the text of the paragraph:', lead.textContent);
console.log('the text of the box:', box.textContent.trim());
lead.textContent = 'a <b>literal</b> tag';
console.log('after the write:', lead.textContent);
console.log('the markup is escaped:', lead.outerHTML);
console.log('elements inside the paragraph:', lead.children.length);
node text.js
the text of the paragraph: Hello world
the text of the box: Hello world
after the write: a <b>literal</b> tag
the markup is escaped: <p class="lead">a <b>literal</b> tag</p>
elements inside the paragraph: 0
The paragraph held a bold child before the write and holds none after it, and the serialiser turned the angle brackets of the string into < and >, which is how HTML carries them as text. The text reads back exactly as it was written, with the tags visible, and that is the behaviour a page wants for a comment or a file name.
innerHTML and why it needs care
innerHTML does the opposite: the string is parsed by the same parser that read the page, so <p>one</p> becomes a real paragraph and a <b> becomes a real bold element. That makes it the tool for a template the program itself composed, and the wrong tool for text that came from a reader: whatever markup the text contains becomes part of the page, including an image with an error handler. The rule of this lesson is one line: textContent for a value, innerHTML for markup the program wrote.
The program fills the card with two paragraphs of markup, then writes the same user string twice, once as markup and once as text, and counts the elements each time.
The file html.js:
const { JSDOM } = require('jsdom');
const html = '<!doctype html><body><div id="box"><p>empty</p></div></body>';
const dom = new JSDOM(html, { url: 'http://localhost/' });
const { document } = dom.window;
const box = document.querySelector('#box');
box.innerHTML = '<p>one</p><p>two <b>bold</b></p>';
console.log('the elements inside:', box.children.length);
console.log('the bold one:', box.querySelector('b').textContent);
console.log('the markup:', box.innerHTML);
console.log('the paragraphs:', box.querySelectorAll('p').length);
const user = '<img src="x.png" alt="a picture">';
box.innerHTML = user;
console.log('user text as markup makes an element:', box.children.length);
console.log('the tag that appeared:', box.firstElementChild.tagName.toLowerCase());
console.log('the attribute:', box.firstElementChild.getAttribute('alt'));
box.textContent = user;
console.log('user text as text makes none:', box.children.length);
console.log('and it reads back unchanged:', box.textContent === user);
node html.js
the elements inside: 2
the bold one: bold
the markup: <p>one</p><p>two <b>bold</b></p>
the paragraphs: 2
user text as markup makes an element: 1
the tag that appeared: img
the attribute: a picture
user text as text makes none: 0
and it reads back unchanged: true
The same string is a picture in one line and five harmless characters in the next, and only the second one is safe for a value that a reader typed. Reading innerHTML is the reverse trip: the parser normalises the markup, so the string that comes back is the page as the browser sees it, not the string that was written.
The class attribute
classList is the list behind the class attribute, with add, remove, toggle, replace and contains. Each method changes the attribute itself, so the stylesheet applies at once and className shows the new value. A class is a single token: a string with a space in it is two classes in the attribute and one invalid argument for the method, which is the error at the end of the program.
The program moves the card through four classes, asks for one and prints the list after each step.
The file classes.js:
const { JSDOM } = require('jsdom');
const html = '<!doctype html><body><div id="box" class="card wide"></div></body>';
const dom = new JSDOM(html, { url: 'http://localhost/' });
const { document } = dom.window;
const box = document.querySelector('#box');
console.log('the class attribute:', box.className);
box.classList.add('raised');
console.log('after add:', box.className);
console.log('contains raised:', box.classList.contains('raised'));
box.classList.remove('card');
console.log('after remove:', box.className);
console.log('toggle on and off:', box.classList.toggle('hidden'), box.classList.toggle('hidden'));
box.classList.replace('wide', 'narrow');
console.log('after replace:', box.className);
console.log('how many classes:', box.classList.length);
try {
box.classList.add('two words');
} catch (error) {
console.log('the error:', error.name, '-', error.message);
}
node classes.js
the class attribute: card wide
after add: card wide raised
contains raised: true
after remove: wide raised
toggle on and off: true false
after replace: narrow raised
how many classes: 2
the error: InvalidCharacterError - The token provided contains HTML space characters, which are not valid in tokens.
toggle answers with the state it left behind, which is why the two calls print true and then false; a program that only wants to turn a class on calls add, and one that only wants to know the state calls contains. The error names the character that is not allowed, and the fix is one class per call.
data attributes and dataset
An attribute that starts with data- is a place for a value the page needs and no reader sees. dataset maps those attributes to camelCase properties: data-note-count is dataset.noteCount, and a write to the property writes the attribute. The value is always a string, so a number is converted on the way in and parsed on the way out, and a name that does not exist answers undefined rather than an error.
The program reads an attribute from the markup, writes two, reads them back through both names and counts the data attributes of the element.
The file data.js:
const { JSDOM } = require('jsdom');
const html = '<!doctype html><body><div id="box" data-id="7"></div></body>';
const dom = new JSDOM(html, { url: 'http://localhost/' });
const { document } = dom.window;
const box = document.querySelector('#box');
console.log('an attribute from the markup:', box.dataset.id);
console.log('the same value as an attribute:', box.getAttribute('data-id'));
box.dataset.state = 'open';
box.dataset.noteCount = '3';
console.log('after two writes:', box.getAttribute('data-state'), box.getAttribute('data-note-count'));
console.log('the camelCase key reads it back:', box.dataset.noteCount);
console.log('a key that is not there:', box.dataset.missing);
console.log('how many data attributes:', Object.keys(box.dataset).length);
node data.js
an attribute from the markup: 7
the same value as an attribute: 7
after two writes: open 3
the camelCase key reads it back: 3
a key that is not there: undefined
how many data attributes: 3
The hyphen and the capital are the same attribute in two spellings, and the third one came from the markup. The count is what a program can use to walk the state of an element, and the undefined is the reminder that a missing data attribute is not an error until a program reads a property of it.
Exercises
- Write the string a & b with textContent and print outerHTML. How is the ampersand stored?
- Put a <script> element into the card with innerHTML and check whether its code runs in jsdom. What does that say about innerHTML as a tool for templates?
- Toggle a class three times and print the result after each call. Which value comes back on the third one?
- Set dataset.count = 2 and read the attribute with getAttribute. What is the difference between the two values?
- Remove a class the element does not have. Does classList.remove throw, and what does the same call do for toggle with its second argument?
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
Which property keeps a string as text and never parses it?
Answer
textContent
A write to textContent makes one text node, so the angle brackets of the string stay characters.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<div id=box></div>", { url: "http://localhost/" }); const box = dom.window.document.querySelector("#box"); box.textContent = "<b>bold</b>"; console.log(box.children.length);Answer
0
textContent never creates an element, so the bold tag stays text and the element has no children.
-
Why is innerHTML a poor choice for text a reader typed?
Answer
The text is parsed as markup and can add elements to the page
The parser turns the typed angle brackets into elements, and an element can carry a handler.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<div id=box class=card></div>", { url: "http://localhost/" }); const box = dom.window.document.querySelector("#box"); console.log(box.classList.toggle("hidden"), box.classList.toggle("hidden"));Answer
true false
toggle reports the state it leaves, so the first call adds the class and the second one removes it.
-
Which property of dataset holds the attribute data-note-count?
Answer
noteCount
Each hyphen and the letter after it become one capital letter in the property name.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<div id=box data-id=7></div>", { url: "http://localhost/" }); console.log(typeof dom.window.document.querySelector("#box").dataset.id);Answer
string
Every attribute value is text, so a number in a data attribute comes back as a string.
-
What happens on classList.add with a string that contains a space?
Answer
It throws an InvalidCharacterError
A token may not contain a space, so the method refuses the argument instead of splitting it.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<div id=box></div>", { url: "http://localhost/" }); const box = dom.window.document.querySelector("#box"); box.innerHTML = "<b>bold</b> and a word"; console.log(box.textContent);Answer
bold and a word
The tags became an element, and textContent joins the text of the element and the text after it.
-
What does innerHTML give when it is read?
Answer
The markup of the children as the parser normalised it
The serialiser writes the current tree, so quotes and empty tags may look different from the source.
-
What does this program print?
const { JSDOM } = require("jsdom"); const dom = new JSDOM("<div id=box class=card></div>", { url: "http://localhost/" }); const box = dom.window.document.querySelector("#box"); box.classList.add("wide"); console.log(box.className);Answer
card wide
The new class is appended to the attribute, and className reads the attribute as one string.
The programs on this page were run with Node.js 24.22.1 against jsdom 30.1.3 and linted with ESLint 10.14.0 on Alpine Linux 3.24.3 (x86_64) in a Docker container.
Article author: Arthur Isaev