The browser side that Flask pages feed.
Open the interactive lessons →Frontend Web Technologies (HTML, CSS, JavaScript & DOM) past questions
Contents
- Start here: HTML, CSS and JavaScript, from zero
- HTML structure, lists and linking scripts
- Which CSS rule wins
- Attribute selectors
- :valid and :invalid
- HTML5 validation attributes and JavaScript checks
- JavaScript output: alert, console, document.write, innerHTML
- JSON syntax and parsing
- 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 mentions | Layer |
|---|---|
| tags, attributes, nesting, forms | HTML |
| selectors, colours, which rule wins, sizes | CSS |
| alert, console.log, innerHTML, events, fetch | JavaScript |
| { } with quoted keys sent between programs | JSON (data, not a page language) |
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) a tag with an attribute: HTML.
- (2) a selector and a declaration: CSS.
- (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.
- Before the click: Hello, red.
- The click handler sets textContent to Clicked.
- 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
| Step | Do this |
|---|---|
| 1 | Ask what the question is about: content, look or behaviour. |
| 2 | Content points to HTML, look to CSS, behaviour to JavaScript. |
| 3 | For output questions, follow the page top to bottom. |
| 4 | Apply 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.
- The script runs before the body has been read.
- No element with id
texists yet, so the call returnsnull. - Setting a property on
nullraises an error. - 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.
If a script touches an element, check that the element appears earlier, or that the code waits for an event.
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?
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
| Language | Job | Example |
|---|---|---|
| HTML | content and structure | <h1>, <p>, <ul>, <form> |
| CSS | presentation (styling) | p { color: blue; } |
| JavaScript | behaviour, optional extras | alert("hi"), changing the page |
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
| Tag | Shows | Use when |
|---|---|---|
<ul> | bullets | the order does not matter (ingredients) |
<ol> | numbers 1, 2, 3 | the order matters (cooking steps) |
<dl> | terms with descriptions | a 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.
- Steps:
<ol>. - 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.
<script src=...>is the standard way.hrefon<script>is ignored by the browser.<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 in | Examples | Why |
|---|---|---|
<head> | <title>, <link rel="stylesheet">, <meta> | information about the page, loaded before it shows |
<body> | headings, paragraphs, forms, images | what 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.
- The outer list is ordered and has two items.
- Tea gets number 1.
- Milk sits in an unordered list inside item 1, so it gets a bullet.
- Rice is the second item of the outer list, so it gets number 2.
Answer.
- Tea, a bulleted Milk under it, 2. Rice.
Common mistake.
Numbering Milk as 2.
Count only the direct li children of a list to find its numbers.
Open, nest, close in reverse order.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Find the element and its parent. |
| 2 | Check that tags close in the right order. |
| 3 | Pick 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?
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 is | Example | Strength |
|---|---|---|
inline style attribute | <p style="color:black"> | strongest |
| id selector | #para { color: red; } | high |
| class selector | .text { color: green; } | medium |
| tag selector | p { 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.
- Both rules match the element.
- The class selector is more specific than the tag selector.
- 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.
- Both selectors have the same specificity (one class).
- 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 present | Colour shown | Why |
|---|---|---|
p, .c, #i | the #i colour | id beats class beats tag |
the same plus style="..." on the element | the inline colour | inline 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.
- Both rules apply to the paragraph.
- 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-sizing | Visible width |
|---|---|
| content-box (default) | 100 + 2×10 + 2×2 = 124 px |
| border-box | 100 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.
- Each box is 124 px wide.
- 3 × 124 = 372 px > 300 px.
- 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.
- Both selectors are single classes.
.bis written later in the CSS.- The order inside
classdoes not matter.
Answer.
Blue.
Common mistake.
Answering red because a is written last on the element.
- 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.
Inline, then id, then class, then tag; ties go to the later rule.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | List every rule that matches. |
| 2 | Compare their specificity. |
| 3 | On a tie, take the later one. |
| 4 | An 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?
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
| Selector | Matches when the attribute | out matches | out-text / outcontent |
|---|---|---|---|
[a=v] | equals v exactly | yes | no |
[a~=v] | contains v as a whole space-separated word | yes | no |
[a*=v] | contains v anywhere | yes | yes |
[a^=v] | starts with v | yes | yes |
[a|=v] | is v or starts with v- | yes | out-text yes |
Why it works this way. Attributes carry structured text, so selectors offer several ways to compare it.
How to answer
| Step | Do this |
|---|---|
| 1 | Write the attribute value of each element as plain text. |
| 2 | Read the operator before the equals sign. |
| 3 | Test the text, remembering that ~= needs a whole word. |
| 4 | Check 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
| Selector | Matches 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.
box out→ wordsbox,out: match.outbox→ one wordoutbox: no match.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 and 2 contain the word
new: red. newestis a different word: no style.hot-itemis one word: no border.item hotcontainshot: 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.
- Both values contain the whole word
btn. - The first value begins with
btn. - The second begins with
primary.
Answer.
~= matches both; ^= matches only the first.
Common mistake.
Treating ^= as if it tested every class name separately.
~= is about words. ^=, $= and *= are about characters.
~= 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?
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.
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?
| Field | Empty | Some text |
|---|---|---|
| no constraints | valid | valid |
required | invalid | valid |
minlength="8" (not required) | valid (empty is allowed) | invalid while under 8 typed characters |
required minlength="5" | invalid | invalid 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
| Step | Do this |
|---|---|
| 1 | List the constraints on the field. |
| 2 | If the field is empty, only required can make it invalid. |
| 3 | Otherwise test every constraint against the typed value. |
| 4 | Pick 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.
- Empty: no rule fails, so green.
- 2 typed characters: fewer than 6, so red.
- 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.
- Characters 1–3: red.
- Characters 4–6: green.
- 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.
- Empty: no rule is broken, so green.
- 0 is below the minimum: red.
- 10 equals the maximum, which is allowed: green.
- 11 is above the maximum: red.
Answer.
Green, red, green, red.
Common mistake.
Colouring the empty optional field red.
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
| Field | Valid? | Rule broken |
|---|---|---|
type="email" value="x" | false | not an email address |
required and empty | false | a value is required |
pattern="[0-9]{3}" value="12a" | false | does not match the pattern |
type="email" value="a@b.co" | true | none |
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?
A form with boxes marked "required": the clerk hands it back before it ever reaches the office.
Validation attributes
| Attribute | Blocks submit when | Browser message (en-US) |
|---|---|---|
required | the field is empty | Please fill out this field. |
minlength="n" | fewer than n typed characters | Please lengthen this text… |
maxlength="n" | (typing is stopped at n) | none |
type="email" | not an email address | Please 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.
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.
requiredfails, so the browser shows its own message beside the field (the wording depends on the browser).- The submit event does not fire, so
checkand 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.
- The function runs in the user's browser before any request.
- 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 attributes | JavaScript | Server (Flask) | |
|---|---|---|---|
| Runs | in the browser, before submit | in the browser, when you call it | after the request arrives |
| Can be skipped | yes (curl, edited page) | yes | no |
| Good for | quick feedback | custom rules | safety 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.
- No page is loaded.
- No attribute is read.
- Only the server's own check applies.
Answer.
No.
Common mistake.
Relying on required to protect the data.
- Check in order: HTML5 attributes first, then JavaScript, then the server.
- A
patternmust match the whole value, not just a part of it. - An empty optional field is not checked against
pattern.
Browser first, script second, server always.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Check the attributes. |
| 2 | Then the submit script. |
| 3 | Then 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?
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
| Code | Shows 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.
console.logwrites only to the developer tools.- The element
msgnow showsSaved. - No dialog opens, because
alertwas 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.
- The page has finished loading.
document.writethen replaces the whole document.- 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> element | yes | no |
| Page shows | x in bold | <b>x</b> as text |
| el.innerHTML afterwards | <b>x</b> | <b>x</b> |
How to answer
| Step | Do this |
|---|---|
| 1 | Find the method name. |
| 2 | Decide where it writes. |
| 3 | Run the statements in order. |
| 4 | Remember 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.
- After the first line the element shows an italic a.
- Reading
textContentgives justa. - The new string is
a<b>. - Writing it as
textContentremoves 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.
Tags become elements only through innerHTML or document.write.
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?
JSON accepts one spelling only: double quotes, no spare commas and lowercase true, false and null. One slip rejects the whole text.
JSON rules
| Rule | Valid | Invalid |
|---|---|---|
| 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' |
| literals | true, false, null | True, 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.
- The first holds an array of numbers: valid.
- The second puts
"k": 1inside[ ]: invalid. - 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.
obj.pagesis the number 120.- Adding a string turns it into text.
obj.nameisnotebook.
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
| Text | Result |
|---|---|
{"a":1} | ok |
{'a':1} | error: single quotes |
[1,2,] | error: trailing comma |
{a:1} | error: key not quoted |
"hi" or null | ok: 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
| Step | Do this |
|---|---|
| 1 | Check that every key and string uses double quotes. |
| 2 | Look for a trailing comma. |
| 3 | Check that arrays hold values without keys. |
| 4 | After 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.
o.ais the string "1" because it was quoted.o.bis the number 2.- A string plus a number joins them: "12".
- Two numbers add: 4.
Answer.
"12" and 4.
Common mistake.
Answering 3 for the first.
Quotes in the JSON mean a string in the program.
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?
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
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.
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 (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 reload | AJAX | |
|---|---|---|
| Page during the request | blank or frozen | still usable |
| Data sent back | the whole HTML page | only what changed (often JSON) |
| What updates | everything | one 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.
- The list is captured with 1 item.
- Adding items later does not change a static list.
- So
1is 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.
- The request runs while the user keeps typing.
- The code adds items to the list only; the page is not reloaded.
- 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.
- a is live: 3 + 2 = 5.
- 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.
- The list was made when there were 2 items.
- It is not updated afterwards.
Answer.
$2$
Common mistake.
Treating it like the live list from getElementsByTagName.
getElementsBy...collections update themselves; the result ofquerySelectorAllis 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.
Change the tree and the screen follows.
Method for any exam question
| Step | Do this |
|---|---|
| 1 | Find the element. |
| 2 | Read or change it. |
| 3 | For new data, request it in the background and update part of the tree. |