JavaScript and the DOM: Building the Menu from Data
Use JavaScript to find elements, create new ones from data, change classes, and learn why textContent is safe and innerHTML is dangerous, with the results checked by parsing the output again in Python.
In this lesson you will
- Select and change elements
- Create elements from an array
- Use classList and dataset
- Choose textContent over innerHTML
About 28 minutes
One list, many breads
Ravi’s bread list changes every morning, and he does not want to edit HTML every day. JavaScript can build the list from data. The DOM gives JavaScript a handful of tools. querySelector and querySelectorAll find elements with the same selectors that CSS uses. document.createElement makes a new element, textContent sets its text, and appendChild or append puts it in the tree. classList adds, removes and toggles classes, which is how scripts change appearance without touching styles, and dataset reads data-* attributes, a place to keep extra information in the HTML.
There is one rule that matters for security. textContent treats its value as plain text, so any angle brackets in it are shown as characters. innerHTML treats its value as HTML and parses it, so if the string came from a visitor, a comment or a database, it can contain a tag with an event handler and run the attacker’s script. This is cross-site scripting, XSS, one of the most common web vulnerabilities. Ravi’s rule is simple: build text with textContent, and use innerHTML only for strings that you wrote yourself.
const { JSDOM } = require('jsdom');
const dom = new JSDOM('<!doctype html><body><ul id="bread"></ul><ul id="unsafe"></ul></body>');
const d = dom.window.document;
const breads = [
{ name: 'Sourdough', price: 4.5, left: 12 },
{ name: 'Rye', price: 4.0, left: 3 },
{ name: 'Baguette', price: 2.8, left: 0 },
{ name: '<img src=x onerror=alert(1)>Evil', price: 1, left: 5 },
];
function render(list, parent, safe) {
for (const b of list) {
const li = d.createElement('li');
li.dataset.price = b.price;
if (safe) li.textContent = b.name + ' - ' + b.price.toFixed(2);
else li.innerHTML = b.name + ' - ' + b.price.toFixed(2);
li.classList.toggle('sold-out', b.left === 0);
li.classList.toggle('low', b.left > 0 && b.left < 5);
parent.append(li);
}
}
render(breads, d.getElementById('bread'), true);
render(breads, d.getElementById('unsafe'), false);
const safeHtml = d.getElementById('bread').outerHTML, unsafeHtml = d.getElementById('unsafe').outerHTML;
const summary = {
items: d.querySelectorAll('#bread li').length,
soldOut: [...d.querySelectorAll('#bread .sold-out')].map(x => x.textContent),
low: [...d.querySelectorAll('#bread .low')].map(x => x.textContent.split(' - ')[0]),
priceSum: [...d.querySelectorAll('#bread li')].reduce((s, li) => s + Number(li.dataset.price), 0),
imgSafe: d.querySelectorAll('#bread img').length,
imgUnsafe: d.querySelectorAll('#unsafe img').length,
};
console.log('safe :', safeHtml);
console.log('unsafe:', unsafeHtml);
console.log('DATA ' + JSON.stringify(summary));
safe : <ul id="bread"><li data-price="4.5">Sourdough - 4.50</li><li data-price="4" class="low">Rye - 4.00</li><li data-price="2.8" class="sold-out">Baguette - 2.80</li><li data-price="1"><img src=x onerror=alert(1)>Evil - 1.00</li></ul>
unsafe: <ul id="unsafe"><li data-price="4.5">Sourdough - 4.50</li><li data-price="4" class="low">Rye - 4.00</li><li data-price="2.8" class="sold-out">Baguette - 2.80</li><li data-price="1"><img src="x" onerror="alert(1)">Evil - 1.00</li></ul>
The script built a list of four breads from an array, with one new li for each, a data-price attribute holding the price, and classes chosen with classList.toggle(name, condition): the Baguette, with none left, got sold-out, and breads with fewer than five left got low. The summary read back from the DOM shows 4 items, sold out: Baguette – 2.80, and the total of the data-price values, 12.3, which is 4.5 + 4.0 + 2.8 + 1.0. Reading values back from the DOM, and from dataset, always returns strings, so the script converts them with Number.
The fourth bread has a hostile name, an img tag with an onerror handler. The safe version, built with textContent, shows it as text: in the output, the angle brackets became < and >, and the list has 0 img elements. The unsafe version, built with innerHTML, parsed the string as HTML, so the DOM now contains 1 real img element with an onerror attribute. In a real browser that attribute would run the attacker’s code as soon as the image failed to load. The two lists look identical in the source of the program, with a difference of one property name, which is why this mistake is so common.
Independent check: the two HTML strings produced by jsdom were parsed again by Python’s html.parser, a separate tokeniser. It found four li elements in each list, no img in the safe one and exactly one img, carrying an onerror attribute, in the unsafe one. So the claim does not depend on how jsdom reports its own DOM.
Check by hand: 4.5 + 4.0 + 2.8 + 1 = 12.3. Only the Rye has fewer than five left and more than none, so it is the only “low” item, [‘Rye’]: the hostile item has exactly 5 left, which is not below 5, and the Baguette has 0, so it is sold out instead.
Names, comments, search terms and URL parameters are all untrusted. Use textContent, or a trusted sanitising library with its documentation, and set attributes with setAttribute or properties instead of building HTML strings.
Keep the list of breads as plain data, and write one render function that turns it into elements. When the data changes, render again. This is the idea that frameworks such as React are built on.
Every program in this lesson was run while the course was written, with Node.js 22, jsdom 31 (a pure-JavaScript DOM used for tests, not a real browser) and Python 3.13. Browsers, tools and their menus change often, so check the official documentation (MDN, the Node.js docs, your provider) for current behaviour.
Practice
Add a button to each item that toggles a class named favourite. Sort the breads by price and render again. Try to break the page with a name containing a quotation mark, and see how textContent copes.
Check what you learned
Five quick questions. Pick an answer and you will see straight away whether it is right and why.
Which property is safe for untrusted text?
- innerHTML
- outerHTML
- textContent
- insertAdjacentHTML with HTML
It never parses HTML.
What does classList.toggle(“x”, cond) do?
- Always adds it
- Adds the class if cond is true, removes it otherwise
- Always removes it
- Renames it
The second argument forces the state.
What type does dataset.price return?
- A number
- A string
- A boolean
- An array
Convert with Number.
What is XSS?
- Running an attacker’s script in your page
- A CSS feature
- A server
- A font
Cross-site scripting.
Why parse the output again in Python?
- To confirm the result with a separate parser
- To make it faster
- To format it
- It is required
An independent check.
Summary
- JavaScript finds, creates and changes elements of the DOM.
- classList and dataset change appearance and store extra data.
- textContent is safe, innerHTML is dangerous with untrusted text.
- Keep data separate from the code that displays it.
Questions
Is JavaScript the same as Java?
No. They are different languages with a similar name for historical reasons.
What is the difference between querySelector and getElementById?
querySelector accepts any CSS selector and returns the first match. getElementById only finds an id, and is slightly faster, but the difference rarely matters.
Why do frameworks exist?
To keep the page in sync with changing data without writing every DOM update by hand. The core ideas are the same as in this lesson.
