Frontend Web Technologies (HTML, CSS, JavaScript & DOM)

The browser side that Flask pages feed.

9 lessons · 16 past questions · 49 marks in the papers collected here

Open the interactive lessons →Frontend Web Technologies (HTML, CSS, JavaScript & DOM) past questions

Diagrams, animations, quizzes and checked solutions are on the interactive pages.

Contents

  1. Start here: HTML, CSS and JavaScript, from zero
  2. HTML structure, lists and linking scripts
  3. Which CSS rule wins
  4. Attribute selectors
  5. :valid and :invalid
  6. HTML5 validation attributes and JavaScript checks
  7. JavaScript output: alert, console, document.write, innerHTML
  8. JSON syntax and parsing
  9. The DOM, live collections and AJAX

1. Start here: HTML, CSS and JavaScript, from zero

HTML says what is on the page, CSS says how it looks, JavaScript says what it does.

the three languages of a web page and how they meet

The question this lesson answers. A page misbehaves. Is the cause its content, its looks or its behaviour?

A browser receives three kinds of file. HTML describes the content as a tree of elements. CSS is a list of rules, each choosing some elements with a selector and setting how they look. JavaScript runs in the browser and can read and change the elements, react to clicks, and fetch new data.

Why it works this way. Keeping the three jobs in three languages lets each change without breaking the others.

<!DOCTYPE html>
<html>
<head>
  <title>Demo</title>
  <style> h1 { color: red; } </style>
</head>
<body>
  <h1 id="t">Hello</h1>
  <button id="b">Change</button>
  <script>
    document.getElementById("b").addEventListener("click", function () {
      document.getElementById("t").textContent = "Clicked";
    });
  </script>
</body>
</html>

Which layer is the question about?

Question mentionsLayer
tags, attributes, nesting, formsHTML
selectors, colours, which rule wins, sizesCSS
alert, console.log, innerHTML, events, fetchJavaScript
{ } with quoted keys sent between programsJSON (data, not a page language)
Picture it

A web page is a house: HTML is the walls and rooms, CSS is the paint and furniture, JavaScript is the electricity that makes things move. The analogy stops at order: the browser reads all three as the page loads, and a script that runs too early may find a room not built yet.

Worked example: Name the layer

Problem.

(1) <input required> (2) p { margin: 0 } (3) alert("hi").

Idea.

Tags are HTML, rules are CSS, function calls are JavaScript.

  1. (1) a tag with an attribute: HTML.
  2. (2) a selector and a declaration: CSS.
  3. (3) a function call: JavaScript.

Answer.

HTML, CSS, JavaScript

Common mistake.

Calling (1) JavaScript because it validates: required is an HTML attribute the browser checks.

Worked example: What does the button do?

Problem.

The page above loads; the user clicks Change once.

Idea.

CSS keeps applying; JavaScript changes only the text.

  1. Before the click: Hello, red.
  2. The click handler sets textContent to Clicked.
  3. The CSS rule still applies: red.

Answer.

Clicked, in red

Common mistake.

Expecting the colour to reset: changing text does not change which CSS rules match.

How a page comes alive: browser reads the HTML, then CSS rules are applied, then JavaScript runs, then events change the page

How to answer

StepDo this
1Ask what the question is about: content, look or behaviour.
2Content points to HTML, look to CSS, behaviour to JavaScript.
3For output questions, follow the page top to bottom.
4Apply each click after the page has loaded.

Worked example: A script that runs too early

Problem.

A script in head runs document.getElementById("t").textContent = "Hi" at once. The element with id t is written later in body. What does the user see?

Idea.

The browser reads the page from top to bottom.

  1. The script runs before the body has been read.
  2. No element with id t exists yet, so the call returns null.
  3. Setting a property on null raises an error.
  4. The page then shows the original text.

Answer.

The original text, with an error in the console.

Common mistake.

Assuming the browser reads the whole page before running any script.

Check your answer in ten seconds

If a script touches an element, check that the element appears earlier, or that the code waits for an event.

Memory line

HTML is what, CSS is how it looks, JavaScript is what it does.

2. HTML structure, lists and linking scripts

HTML says what is on the page; CSS says how it looks; JS says what it does.

what HTML is for, list tags, and how a page loads an external script

The question this lesson answers. How do tags describe the structure of a page, and how is a script attached?

Boxes inside boxes

Every element is a box that sits wholly inside one parent box. Closing tags are the lids, and lids must close in the reverse order of opening.

How a page is put together: html element, then head: title and links, then body: what is shown, then script runs against the body

Why it works this way. A tree of nested elements lets the browser, style rules and scripts all find the same parts.

Three languages of the frontend

LanguageJobExample
HTMLcontent and structure<h1>, <p>, <ul>, <form>
CSSpresentation (styling)p { color: blue; }
JavaScriptbehaviour, optional extrasalert("hi"), changing the page
Notice

JavaScript is optional: a page made only of HTML and CSS works. So "JavaScript is always the core part of a frontend" is false, while "JavaScript provides additional functionality" is true.

Lists and an external script

<h3>Ingredients</h3>
<ul>
  <li>rice</li>
  <li>salt</li>
</ul>
<h3>Steps</h3>
<ol>
  <li>Wash the rice</li>
  <li>Boil it</li>
</ol>
<script src="jsfile.js"></script>

List tags

TagShowsUse when
<ul>bulletsthe order does not matter (ingredients)
<ol>numbers 1, 2, 3the order matters (cooking steps)
<dl>terms with descriptionsa glossary of <dt> / <dd> pairs

Worked example: Choosing list tags

Problem.

A help page shows installation steps that must be done in sequence, and a set of related links in no particular order.

Idea.

Order matters → ordered list.

  1. Steps: <ol>.
  2. Links: <ul>.

Answer.

<ol> for the steps, <ul> for the links

Common mistake.

Using <dl>, which is for term and description pairs.

Worked example: Linking a script

Problem.

Which line loads jsfile.js: <script src="jsfile.js"></script>, <script href="jsfile.js"></script>, <import src="jsfile.js">?

Idea.

Scripts use src; href belongs to <a> and <link>; there is no <import> tag.

  1. <script src=...> is the standard way.
  2. href on <script> is ignored by the browser.
  3. <import> is not an HTML element.

Answer.

<script src="jsfile.js"></script>

Common mistake.

Using href because CSS files use <link href>.

A page is a tree. The browser reads HTML into a tree: <html> holds <head> (title, styles, scripts that load first) and <body> (what you see). Every element sits inside exactly one parent. CSS selectors and JavaScript both find elements by walking this tree, which is why correct nesting matters.

Where things go

Put inExamplesWhy
<head><title>, <link rel="stylesheet">, <meta>information about the page, loaded before it shows
<body>headings, paragraphs, forms, imageswhat the user sees
end of <body><script src="app.js"> (without defer)the elements exist before the script looks for them

Worked example: A list inside a list

Problem.

What is shown for <ol><li>Tea<ul><li>Milk</li></ul></li><li>Rice</li></ol>?

Idea.

Each list numbers or bullets only its own items.

  1. The outer list is ordered and has two items.
  2. Tea gets number 1.
  3. Milk sits in an unordered list inside item 1, so it gets a bullet.
  4. Rice is the second item of the outer list, so it gets number 2.

Answer.

  1. Tea, a bulleted Milk under it, 2. Rice.

Common mistake.

Numbering Milk as 2.

Check your answer in ten seconds

Count only the direct li children of a list to find its numbers.

Memory line

Open, nest, close in reverse order.

Method for any exam question

StepDo this
1Find the element and its parent.
2Check that tags close in the right order.
3Pick the list type by whether order matters.

3. Which CSS rule wins

The most specific rule wins; inline style beats them all.

what happens when several CSS rules set the same property

The question this lesson answers. Two rules set different colours on one element. Which colour appears?

Picture it

Instructions from a school, a teacher and a note on your own desk: the more specific instruction wins.

Which rule wins: find every rule that matches, then inline style beats the rest, then then compare ids, classes, tags, then a tie goes to the later rule

A CSS rule is a selector plus declarations: p { color: blue; }. When several rules set the same property on one element, the browser picks one by specificity: how precisely the selector targets the element.

Why it works this way. A rule aimed at one particular element says more about what the author meant than a rule for every element of a kind, so it wins.

Specificity, strongest first

Where the style isExampleStrength
inline style attribute<p style="color:black">strongest
id selector#para { color: red; }high
class selector.text { color: green; }medium
tag selectorp { color: blue; }low
<style>
  p { color: blue; }
  .text { color: green; }
  #para { color: red; }
</style>
<p id="para" class="text" style="color: black;">IITM BS Degree Program</p>

Worked example: Class versus tag

Problem.

p { color: blue } and .note { color: green }; the element is <p class="note">Hi</p>. Colour?

Idea.

A class is more specific than a tag.

  1. Both rules match the element.
  2. The class selector is more specific than the tag selector.
  3. Green wins.

Answer.

green

Common mistake.

Choosing blue because p comes first or last.

Worked example: Equal specificity: the later rule

Problem.

.a { color: red } then .b { color: purple }, element <p class="a b">. Colour?

Idea.

Two class selectors tie; the one written later wins.

  1. Both selectors have the same specificity (one class).
  2. The later rule in the stylesheet, .b, wins.

Answer.

purple

Common mistake.

Thinking the order of classes in class="a b" matters.

The full ladder of who wins. Compare in this order and stop at the first difference: !important rules, then the inline style attribute, then id selectors, then class (and attribute, pseudo-class) selectors, then tag selectors. Only when everything is equal does the rule written later win.

One paragraph, rules piled up

Rules presentColour shownWhy
p, .c, #ithe #i colourid beats class beats tag
the same plus style="..." on the elementthe inline colourinline beats any selector
the same plus p{...!important}the !important colour!important beats inline

Worked example: Inline or id?

Problem.

#i{color:red} in a stylesheet; <p id="i" style="color:blue">.

Idea.

Inline style outranks every selector.

  1. Both rules apply to the paragraph.
  2. Inline style wins over the id rule.

Answer.

blue

Common mistake.

Choosing red because ids are the strongest selector: inline style is above all selectors.

The box model: how wide is a box? Every element is a box: content, then padding, then border, then margin. By default (box-sizing: content-box) the width you set is the content only, so padding and border are added on top. With box-sizing: border-box the width you set includes padding and border.

width: 100px; padding: 10px; border: 2px

box-sizingVisible width
content-box (default)100 + 2×10 + 2×2 = 124 px
border-box100 px

Worked example: Will it fit?

Problem.

A 300 px column holds three boxes, each width: 100px; padding: 10px; border: 2px with default box-sizing.

Idea.

Each box is wider than its width value.

  1. Each box is 124 px wide.
  2. 3 × 124 = 372 px > 300 px.
  3. They wrap; with border-box each is 100 px and they fit.

Answer.

No (372 px); yes with border-box

Common mistake.

Adding only the widths (300 px).

Worked example: Order in the class attribute

Problem.

CSS has .a {color: red} then .b {color: blue}. An element has class="b a". What colour is it?

Idea.

Equal strength is settled by order in the style sheet.

  1. Both selectors are single classes.
  2. .b is written later in the CSS.
  3. The order inside class does not matter.

Answer.

Blue.

Common mistake.

Answering red because a is written last on the element.

Tips and tricks
  • Count ids, then classes, then tags. Compare the counts from left to right.
  • Source order matters only when specificity is exactly equal.
  • Properties are decided one by one, so one element can take colour from one rule and size from another.
Memory line

Inline, then id, then class, then tag; ties go to the later rule.

Method for any exam question

StepDo this
1List every rule that matches.
2Compare their specificity.
3On a tie, take the later one.
4An inline style beats these.

4. Attribute selectors

~= means "has this whole word in its list".

selectors such as [id~=out] and [class=out]

The question this lesson answers. How can a rule choose elements by part of an attribute's text?

Searching a name tag

Each operator asks a different question about the text on a tag: is it exactly this, is this one of its words, does it begin or end this way, or does it appear anywhere?

Reading an attribute selector: pick elements with the attribute, then read the operator, then compare the attribute value, then style the elements that pass

Attribute selectors

SelectorMatches when the attributeout matchesout-text / outcontent
[a=v]equals v exactlyyesno
[a~=v]contains v as a whole space-separated wordyesno
[a*=v]contains v anywhereyesyes
[a^=v]starts with vyesyes
[a|=v]is v or starts with v-yesout-text yes

Why it works this way. Attributes carry structured text, so selectors offer several ways to compare it.

How to answer

StepDo this
1Write the attribute value of each element as plain text.
2Read the operator before the equals sign.
3Test the text, remembering that ~= needs a whole word.
4Check every element, not just the first match.

Attribute selectors in one table. Square brackets select by attribute. The operator decides how the value is compared: equal, contains a whole word, starts with, ends with, or contains anywhere.

Attribute operators

SelectorMatches when the attribute
[type]exists at all
[type="email"]equals email exactly
[class~="btn"]has btn as one whole word in a space-separated list
[href^="https"]starts with https
[href$=".pdf"]ends with .pdf
[href*="iitm"]contains iitm anywhere

Worked example: Whole words

Problem.

[class~=out] against class="box out", class="outbox", class="out". Which match?

Idea.

Split the value at spaces; look for the exact word.

  1. box out → words box, out: match.
  2. outbox → one word outbox: no match.
  3. out → match.

Answer.

box out and out

Common mistake.

Matching outbox as a substring.

Worked example: Which items get a colour?

Problem.

[data-tag~="new"] makes text red; [class~="hot"] adds a yellow border. Items: (1) data-tag="new", (2) data-tag="new sale", (3) data-tag="newest", (4) class="hot-item", (5) class="item hot".

Idea.

~= matches one whole word in a space-separated value.

  1. 1 and 2 contain the word new: red.
  2. newest is a different word: no style.
  3. hot-item is one word: no border.
  4. item hot contains hot: yellow border.

Answer.

Red: 1 and 2. Yellow border: 5.

Common mistake.

Matching parts of words.

Worked example: Order of class names

Problem.

Elements have class="btn primary" and class="primary btn". Which match [class~=btn], which match [class^=btn]?

Idea.

~= looks for a word anywhere; ^= looks at the very start of the text.

  1. Both values contain the whole word btn.
  2. The first value begins with btn.
  3. The second begins with primary.

Answer.

~= matches both; ^= matches only the first.

Common mistake.

Treating ^= as if it tested every class name separately.

Check your answer in ten seconds

~= is about words. ^=, $= and *= are about characters.

Memory line

~= is a word; ^= starts; $= ends; *= anywhere.

5. :valid and :invalid

:valid and :invalid follow the field's state live.

how CSS can colour form fields by whether they pass their constraints

The question this lesson answers. When exactly does a field count as valid, while the user is still typing?

A gate with rules

Each constraint is a rule at the gate. A field is valid only when no rule is broken. A field with nothing in it breaks only the required rule.

Validity pseudo-classes

input:valid matches a field whose value passes all its constraints (required, minlength, maxlength, type); input:invalid matches one that fails. The match updates live as the user types.

When is a field valid?

FieldEmptySome text
no constraintsvalidvalid
requiredinvalidvalid
minlength="8" (not required)valid (empty is allowed)invalid while under 8 typed characters
required minlength="5"invalidinvalid under 5, valid from 5

Why it works this way. The browser tests the constraints on every change, so the style can guide the user before anything is sent.

Deciding valid or invalid. is the field empty? yes: invalid only if required. no: invalid if any rule is broken

How to answer

StepDo this
1List the constraints on the field.
2If the field is empty, only required can make it invalid.
3Otherwise test every constraint against the typed value.
4Pick the colour from the matching selector.

Worked example: A field with minlength only

Problem.

<input type="text" minlength="6"> is red when :invalid and green when :valid. What colour is it when empty, after typing ab, and after typing nerdhub99?

Idea.

An empty field is allowed because it is not required; minlength judges typed text.

  1. Empty: no rule fails, so green.
  2. 2 typed characters: fewer than 6, so red.
  3. 9 characters: green.

Answer.

green, red, green

Common mistake.

Calling the empty field red: it is not required.

Worked example: Typing past maxlength

Problem.

<input required minlength="4" maxlength="6">, red for invalid and green for valid. The user types python3x one key at a time.

Idea.

minlength decides when it turns green; maxlength stops further typing.

  1. Characters 1–3: red.
  2. Characters 4–6: green.
  3. The 7th and 8th keys add nothing, so it stays green with python.

Answer.

red for 3 keys, then green, staying green

Common mistake.

Expecting red again after 6 characters.

Worked example: A number with limits

Problem.

<input type="number" min="1" max="10"> with :invalid red and :valid green. Colour when empty, with 0, with 10 and with 11?

Idea.

The field is not required.

  1. Empty: no rule is broken, so green.
  2. 0 is below the minimum: red.
  3. 10 equals the maximum, which is allowed: green.
  4. 11 is above the maximum: red.

Answer.

Green, red, green, red.

Common mistake.

Colouring the empty optional field red.

Check your answer in ten seconds

Limits include their end values: min and max themselves are valid.

Asking the browser directly. Every form field has a checkValidity() method that returns true or false using the same rules the browser applies on submit: type, required, pattern, min, max and the length limits. :valid and :invalid style the field from the same answer.

checkValidity() for four fields

FieldValid?Rule broken
type="email" value="x"falsenot an email address
required and emptyfalsea value is required
pattern="[0-9]{3}" value="12a"falsedoes not match the pattern
type="email" value="a@b.co"truenone
Memory line

Empty is a problem only when required.

6. HTML5 validation attributes and JavaScript checks

The browser checks attributes first; your script and the server can check more.

browser-enforced attributes and a JavaScript validation function on submit

The question this lesson answers. The browser, your script and the server can all check a form. In which order, and which can be trusted?

Picture it

A form with boxes marked "required": the clerk hands it back before it ever reaches the office.

Validation attributes

AttributeBlocks submit whenBrowser message (en-US)
requiredthe field is emptyPlease fill out this field.
minlength="n"fewer than n typed charactersPlease lengthen this text…
maxlength="n"(typing is stopped at n)none
type="email"not an email addressPlease include an '@'…

Why it works this way. Checks in the browser give quick feedback, but a request can be sent without the browser, so only the server check protects the data.

Order of checks on submit

When the user presses Submit, the browser first runs HTML5 validation. If a field fails, it shows its message next to that field and does not fire the submit event, so a JavaScript onsubmit function does not run. Only a form that passes reaches your script (client-side JS validation), and then the server (backend validation).

Worked example: Empty required email

Problem.

A form has <input type="email" name="mail" required> and onsubmit="check()", which alerts if the address lacks @iitm. The field is left empty and Submit is pressed. What does the user see?

Idea.

The browser's own validation runs first and blocks the submit event.

  1. required fails, so the browser shows its own message beside the field (the wording depends on the browser).
  2. The submit event does not fire, so check and its alert never run.

Answer.

The browser's "please fill in this field" message

Common mistake.

Expecting the script's alert.

Worked example: Which kind of validation?

Problem.

Is a JavaScript validateForm() run on submit frontend or backend validation?

Idea.

It runs in the browser.

  1. The function runs in the user's browser before any request.
  2. So it is client-side (frontend) validation, not backend processing.

Answer.

Client-side (frontend) validation

Common mistake.

Calling JavaScript "backend".

Three layers of checking. A robust form checks input three times: the browser's attributes (instant, but anyone can bypass them), your JavaScript (custom rules, also bypassable) and the server (the only check an attacker cannot skip). Exam statements that say frontend checks are "enough" are false.

Where a check runs

HTML attributesJavaScriptServer (Flask)
Runsin the browser, before submitin the browser, when you call itafter the request arrives
Can be skippedyes (curl, edited page)yesno
Good forquick feedbackcustom rulessafety and correctness

Your own check before submit. A script can stop a form from being sent: listen for the form's submit event and call e.preventDefault() when the input is wrong. The page stays where it is, and you can show a message. The server must still check again.

The bug in many PYQ forms. onsubmit="validateForm()" without return cannot cancel the submit: even when the function returns false, the form still submits. The correct form is onsubmit="return validateForm()".

form.addEventListener("submit", function (e) {
  if (form.q.value.length < 3) {
    e.preventDefault();      // stay on the page
    msg.textContent = "Type at least 3 characters";
  }
});

Worked example: A check that never runs

Problem.

A form field has required. A program posts to the server directly, without the browser. Is the field still enforced?

Idea.

HTML attributes act only in a browser.

  1. No page is loaded.
  2. No attribute is read.
  3. Only the server's own check applies.

Answer.

No.

Common mistake.

Relying on required to protect the data.

Tips and tricks
  • Check in order: HTML5 attributes first, then JavaScript, then the server.
  • A pattern must match the whole value, not just a part of it.
  • An empty optional field is not checked against pattern.
Memory line

Browser first, script second, server always.

Method for any exam question

StepDo this
1Check the attributes.
2Then the submit script.
3Then the server.

7. JavaScript output: alert, console, document.write, innerHTML

alert → dialog; console → developer tools; innerHTML → part of the page.

where each JavaScript output method shows its text

The question this lesson answers. A script produces text. Where does the user, or the developer, see it?

Four places to speak

A pop-up interrupts the user, the console speaks to the developer, and writing into the document or an element speaks on the page itself.

Where output goes: script runs, then console.log: developer console, then alert: pop-up box, then innerHTML: inside the page

Where output goes

CodeShows text in
alert("Hi")a dialog box (pop-up)
console.log("Hi")the developer console
console.error("Hi")the developer console, as an error
document.write("Hi")the document (after load it replaces the page)
el.innerHTML = "Hi"inside that element
<button onclick="alert('Hello')">One</button>
<button onclick="console.log('Hello')">Two</button>
<p id="out"></p>
<script>
  document.getElementById("out").innerHTML = "Set by JS";
</script>

Why it works this way. Pages, pop-ups and the developer console serve different readers, so each has its own command.

Worked example: What does the user see?

Problem.

A button runs console.log("saved"); document.getElementById("msg").textContent = "Saved";

Idea.

The console is for developers; textContent changes the page.

  1. console.log writes only to the developer tools.
  2. The element msg now shows Saved.
  3. No dialog opens, because alert was not called.

Answer.

Saved in the msg element, and nothing else

Common mistake.

Expecting a pop-up.

Worked example: document.write after load

Problem.

A button runs document.write('Hi') after the page has loaded. What happens?

Idea.

Writing after load opens a new document.

  1. The page has finished loading.
  2. document.write then replaces the whole document.
  3. The page shows only Hi.

Answer.

The page is replaced by Hi

Common mistake.

Expecting Hi to be added at the bottom.

innerHTML versus textContent. Both change what is inside an element, but innerHTML parses the string as HTML, so <b>x</b> becomes a bold x, while textContent treats it as plain text, so the tags appear literally. Use textContent for anything a user typed; innerHTML with user text is how script injection happens.

Setting '<b>x</b>'

el.innerHTML = ...el.textContent = ...
Creates a <b> elementyesno
Page showsx in bold<b>x</b> as text
el.innerHTML afterwards<b>x</b>&lt;b&gt;x&lt;/b&gt;

How to answer

StepDo this
1Find the method name.
2Decide where it writes.
3Run the statements in order.
4Remember that a later write to the same element replaces the earlier content.

Worked example: Reading back after writing

Problem.

Run el.innerHTML = "<i>a</i>" and then el.textContent = el.textContent + "<b>". What does the element show?

Idea.

textContent reads text only and writes text only.

  1. After the first line the element shows an italic a.
  2. Reading textContent gives just a.
  3. The new string is a<b>.
  4. Writing it as textContent removes the italic element and shows the characters as typed.

Answer.

The plain text a<b>, not italic.

Common mistake.

Expecting the italic style to survive.

Check your answer in ten seconds

Tags become elements only through innerHTML or document.write.

Memory line

alert pops up, console logs, innerHTML shows on the page.

8. JSON syntax and parsing

Double-quoted keys in objects, values only in arrays.

what makes text valid JSON and how JavaScript reads it

The question this lesson answers. Why does one stray quote make a whole response unreadable?

A strict form

JSON accepts one spelling only: double quotes, no spare commas and lowercase true, false and null. One slip rejects the whole text.

JSON rules

RuleValidInvalid
keys in double quotes{"a": 1}{a: 1}, {'a': 1}
arrays hold values only[1, "x", true]["k": 1]
strings in double quotes"hi"'hi'
literalstrue, false, nullTrue, None
mixed types in an array[2125551234, "212"]

Why it works this way. Programs read JSON mechanically; allowing only one spelling means every language reads it the same way.

const txt = '{"name":"notebook","type":"ruled","pages":120}';
const obj = JSON.parse(txt);
console.log(obj.name + ", " + obj.pages + ", " + obj.type);

Worked example: Spot the invalid one

Problem.

Which is invalid JSON: {"a": [1, 2]}, {"a": ["k": 1]}, {"a": {"k": 1}}?

Idea.

Key–value pairs belong in objects, not arrays.

  1. The first holds an array of numbers: valid.
  2. The second puts "k": 1 inside [ ]: invalid.
  3. The third nests an object: valid.

Answer.

{"a": ["k": 1]}

Common mistake.

Thinking nesting is not allowed.

Worked example: Order of output

Problem.

With obj above, what does obj.pages + " " + obj.name give?

Idea.

The output follows the order you read the properties, not the order in the JSON text.

  1. obj.pages is the number 120.
  2. Adding a string turns it into text.
  3. obj.name is notebook.

Answer.

120 notebook

Common mistake.

Following the order in the JSON text.

JSON in, JSON out. JSON.parse is strict: keys and strings need double quotes, there are no trailing commas, and bare words are not allowed (except true, false, null). JSON.stringify drops object properties whose value is undefined and writes null for undefined inside an array.

What JSON.parse accepts

TextResult
{"a":1}ok
{'a':1}error: single quotes
[1,2,]error: trailing comma
{a:1}error: key not quoted
"hi" or nullok: any JSON value is allowed at the top
JSON.stringify({a:undefined, b:1, c:[1, undefined]}){"b":1,"c":[1,null]}

Text becomes a value: JSON text, then JSON.parse checks it strictly, then JavaScript value, then types stay as written

How to answer

StepDo this
1Check that every key and string uses double quotes.
2Look for a trailing comma.
3Check that arrays hold values without keys.
4After parsing, note which values are strings and which are numbers.

Worked example: Strings that look like numbers

Problem.

const o = JSON.parse('{"a":"1","b":2}'). What are o.a + o.b and o.b + o.b?

Idea.

Parsing keeps the type written in the JSON.

  1. o.a is the string "1" because it was quoted.
  2. o.b is the number 2.
  3. A string plus a number joins them: "12".
  4. Two numbers add: 4.

Answer.

"12" and 4.

Common mistake.

Answering 3 for the first.

Check your answer in ten seconds

Quotes in the JSON mean a string in the program.

Memory line

Double quotes, no trailing commas.

9. The DOM, live collections and AJAX

Scripts change the page through the DOM; AJAX fetches data without a reload.

the page as a tree of objects, collections that update themselves, and updating part of a page

The question this lesson answers. How does a script change a page that has already loaded, without loading it again?

Picture it

A family tree on a whiteboard: scripts add, remove and rewrite names, and the room sees the change at once.

A script changes the page: HTML is parsed into a tree, then script selects a node, then script changes the node, then the browser redraws the page

DOM

The Document Object Model is the browser's programming interface to the page: an abstract tree of objects (document, elements, text). It can be changed at any time, and although JavaScript is the usual language, the DOM is a language-independent interface.

Live collection

document.getElementsByTagName("li") returns a live HTMLCollection: it is not a snapshot, so its length always reflects the current page. (querySelectorAll returns a static list.)

Why it works this way. The browser keeps the page as a tree of objects; changing an object changes what is drawn.

<ul id="cart"><li>Pen</li><li>Ink</li></ul>
<script>
  let items = document.getElementsByTagName("li");
  document.getElementById("cart").innerHTML += "<li>Pad</li><li>Clip</li>";
  console.log(items.length);
</script>
AJAX

AJAX (Asynchronous JavaScript and XML; today usually JSON) lets JavaScript request data from the server in the background and update part of the page without reloading the whole page. The user can keep working meanwhile, and only a little data is transferred, so the page responds faster.

AJAX versus a full page load

Full reloadAJAX
Page during the requestblank or frozenstill usable
Data sent backthe whole HTML pageonly what changed (often JSON)
What updateseverythingone part of the DOM

Worked example: Live versus static

Problem.

Same as the code above but with document.querySelectorAll("li"). What is logged?

Idea.

querySelectorAll returns a static NodeList.

  1. The list is captured with 1 item.
  2. Adding items later does not change a static list.
  3. So 1 is logged.

Answer.

1

Common mistake.

Answering 3, which is the live collection's answer.

Worked example: While messages arrive

Problem.

A chat page uses fetch every few seconds and appends new messages to a list. The user is half-way through typing a reply.

Idea.

An asynchronous request changes only the parts your code updates.

  1. The request runs while the user keeps typing.
  2. The code adds items to the list only; the page is not reloaded.
  3. So the typed text stays. A full reload would have cleared it.

Answer.

The text stays, because only the list is updated

Common mistake.

Thinking every server request reloads the page.

Live lists and snapshots. getElementsByClassName (and getElementsByTagName) return a live collection: add a matching element and the collection grows. querySelectorAll returns a static snapshot taken at the moment of the call. Loops that add elements while reading a live list can run longer than expected.

var live = document.getElementsByClassName("k");
var stat = document.querySelectorAll(".k");
var n = document.createElement("p");
n.className = "k";
document.body.appendChild(n);
console.log(live.length, stat.length);   // 2 1

Worked example: Count after adding

Problem.

The page has 3 elements with class item. var a = document.getElementsByClassName('item'); var b = document.querySelectorAll('.item'); Then two more .item elements are added.

Idea.

Live versus snapshot.

  1. a is live: 3 + 2 = 5.
  2. b was taken before: 3.

Answer.

5 and 3

Common mistake.

Answering 5 and 5: querySelectorAll does not update.

Events and bubbling. addEventListener("click", fn) runs fn when the element is clicked. A click on a button bubbles up: after the button's own handler, its parent's click handler runs, then the grandparent's. e.stopPropagation() stops the climb.

parent.addEventListener("click", () => log.push("parent"));
child.addEventListener("click", () => log.push("child"));
child.click();   // log: ["child", "parent"]

Why AJAX code runs later. JavaScript finishes the code it is running before handling anything that was waiting. Promise callbacks (such as fetch's .then) run as soon as the current code ends; timers run after those. So code written after a fetch call runs before the fetch's result is handled.

console.log("A");
setTimeout(() => console.log("B"), 0);
Promise.resolve().then(() => console.log("C"));
console.log("D");
// A, D, C, B

Worked example: A list that does not grow

Problem.

const items = document.querySelectorAll("li") finds 2 items. A third li is then added. What is items.length?

Idea.

This method returns a fixed snapshot.

  1. The list was made when there were 2 items.
  2. It is not updated afterwards.

Answer.

$2$

Common mistake.

Treating it like the live list from getElementsByTagName.

Tips and tricks
  • getElementsBy... collections update themselves; the result of querySelectorAll is a snapshot.
  • Trace the script line by line and redraw the small tree after each change.
  • AJAX updates part of a page without reloading all of it.
Memory line

Change the tree and the screen follows.

Method for any exam question

StepDo this
1Find the element.
2Read or change it.
3For new data, request it in the background and update part of the tree.

Practise this topic →

Weeks covering this topic

Other MAD 1 topics