smartyfy.mrindigi.com

Web Development Pro | Lesson 026 | Read and Update the DOM Safely

Web Development Pro · Lesson 26 of 60

Module 3: JavaScript foundations

In this lesson

Prerequisites and learning outcomes

Complete lesson 25 first. This lesson builds on selectors, textcontent, and attributes. By the end, you can connect JavaScript to existing markup without inserting untrusted HTML. Plan 10–15 minutes for the core explanation and additional time for the worked practice.

Connect a calculation to real content

The earlier scripts produced console messages. A visitor needs useful information in the page itself. The Document Object Model, or DOM, represents the parsed document as nodes that JavaScript can inspect and update. It is a browser API rather than a feature of the JavaScript language alone. This distinction explains why a script can run in Node but fail when it expects document.

The DOM is the current document state. It may differ from the original HTML source because the browser repaired markup or scripts changed it. Updating a heading does not automatically edit index.html on disk. Treat the source files as the durable implementation and the DOM as the current page instance produced from them.

Select an element and handle absence

Document.querySelector accepts a CSS selector and returns the first matching element, or null if there is no match. QuerySelectorAll returns a static NodeList of matches. A selector can be syntactically invalid, in which case the API throws instead of returning null. Keep selectors simple and tied to deliberate ids or component hooks.

<h1 id="workshop-title">Workshop details</h1>
<p id="workshop-summary">Read the current fictional workshop information.</p>
const workshop = { id: 'bike-101', title: 'Bicycle basics', capacity: 12 };
const heading = document.querySelector('#workshop-title');
const summary = document.querySelector('#workshop-summary');
if (!heading || !summary) {
  throw new Error('The workshop detail elements are missing.');
}
heading.textContent = workshop.title;
heading.dataset.workshopId = workshop.id;
summary.textContent = `${workshop.capacity} places in this fictional session.`;

The supplied complete page loads this script with defer, so the expected markup has been parsed before selection. The guard makes a broken markup contract explicit rather than allowing a vague property-access error later. A reusable widget might choose to exit quietly when absent, but a required page component should fail in a way developers can diagnose.

Write text as text

TextContent inserts a string as text rather than parsing it as HTML. If a workshop title contains angle brackets, they remain text content. InnerHTML instead parses a string as markup, which is dangerous when the string includes untrusted content. Avoid using HTML parsing merely because a template literal looks convenient.

Safe text insertion is not the same as validating every kind of value. Setting an href from external data needs URL-specific validation; setting CSS or script content has other rules. The safe operation depends on the destination context. For this lesson, titles and descriptions belong in text nodes, so textContent expresses the correct intent directly.

Setting textContent replaces an element's existing child content. If you set it on a paragraph containing a link, the link disappears and is replaced by plain text. Choose the smallest appropriate target, or create separate child elements when some markup must remain. Do not update a whole main region just to change a small count.

Understand attributes and properties

HTML attributes are serialized values in markup. DOM properties expose current object state and can have different types or behavior. For example, an input's value property reflects its current entered value, while its value attribute relates to its initial/default value. Reading the wrong one can make a form handler ignore what the person just typed.

Dataset provides string access to data-* attributes. Dataset.workshopId corresponds to data-workshop-id. It is useful for attaching a harmless stable identifier to an element, but it is public page data. Never store secrets or treat a data attribute as trusted authorization merely because your own script initially wrote it.

ClassList can add, remove, or toggle CSS classes without rebuilding the complete class string. Use a class for a visual state and maintain any required semantic state as well. A class named expanded does not automatically tell assistive technology that a control is expanded; the relevant native or ARIA state must agree with the actual behavior.

Keep selection and rendering predictable

Store references to stable elements that the page owns. If you later replace an entire subtree, an old reference may point to a detached node rather than the visible replacement. Reusing that reference can update something no visitor can see. Either preserve stable containers or deliberately obtain references to newly created elements.

A static NodeList does not automatically gain elements added after querySelectorAll ran. Other collection APIs can be live, so read their contracts instead of assuming all collections behave the same. When in doubt, select again at the point where you need the current set or design your renderer to own the relevant nodes explicitly.

Verify safety and integration separately

The test fixture supplies a small explicit DOM double to run the script and inspect its text assignments. It also tests a title containing markup-like text and a missing required element. Those checks verify the script's calls and contracts in the double; they do not execute a browser parser or prove visual layout and accessibility.

The static HTML check verifies the real page contains the expected ids and script file. Browser practice should confirm the visible heading and summary after load. This combination separates three questions: are the files connected, does the script perform the intended operations, and does the actual browser present them correctly?

Worked practice

Worked exercise 1: Fix a missing selector target

Task: The script selects #workshop-title, but HTML uses id="event-title". Worked answer: align the markup and selector deliberately, then rerun the script. Do not remove the guard simply to hide the error; the underlying component contract is still broken.

Worked exercise 2: Preserve literal text

Task: A fictional title is “Repair <em>together</em>” and should display those characters literally. Worked answer: assign it with textContent. Using innerHTML would interpret em as markup and would create a dangerous pattern if future titles came from an untrusted source.

Worked exercise 3: Read a current form value

Task: A user changes an input, but code reads getAttribute('value') and sees the old value. Worked answer: read the input's value property for its current state. Attribute and property behavior must be understood for the specific element rather than assumed identical.

Knowledge check

Question 1

What does querySelector return when no element matches a valid selector? A) An empty NodeList. B) null. C) An empty element. D) undefined by definition.

Check question 1: answer and explanation

Answer: B. QuerySelector returns one element or null; querySelectorAll has a collection result.

Question 2

Which operation treats a supplied title as literal text? A) textContent assignment. B) innerHTML assignment. C) Parsing it as a template document. D) Inserting it as an HTML string.

Check question 2: answer and explanation

Answer: A. Text insertion avoids interpreting the title as markup.

Question 3

What happens to existing child elements when textContent is assigned? A) They are always preserved. B) Only the first existing text node changes. C) They are replaced by the new text content. D) They stay attached with their listeners but become hidden.

Check question 3: answer and explanation

Answer: C. Use a narrow target when existing child markup must remain.

Question 4

What does dataset.workshopId correspond to? A) The data-workshopId attribute with its original capitalization. B) An id attribute whose value is workshopId. C) A class attribute whose value is workshop-id. D) The data-workshop-id attribute.

Check question 4: answer and explanation

Answer: D. Dataset maps data attributes to string-valued properties.

Question 5

Does a passed DOM-double test prove browser rendering? A) No; it verifies the modeled operations only. B) Yes, because both use JavaScript. C) Yes, if ids match. D) Yes, if no exception occurs.

Check question 5: answer and explanation

Answer: A. A test double does not implement the browser's complete layout and interaction behavior.

Sources and further reading