6. Interacting with the DOM
Lesson objectives
Students learn how to use JS to update the html page (DOM, update input field/element colour)
Students learn how to use JS to handle html events (button click)
Students learn how to use JS to navigate to a different page
Students learn how include JS file in a website
Lesson time to deliever:
1 sessions, 1.5hrs
Lesson content
document.getElementById
If an element has the id
attribute, we can get the element using the method document.getElementById(id)
, no matter where it is.
The id
must be unique
The id
must be unique. There can be only one element in the document with the given id
.
If there are multiple elements with the same id
, then the behavior of methods that use it is unpredictable, e.g. document.getElementById
may return any of such elements at random. So please stick to the rule and keep id
unique.
(maybe don't cover as can be confusing): Also, there’s a global variable named by id
that references the element. So can just do:
querySelectorAll
By far, the most versatile method, elem.querySelectorAll(css)
returns all elements inside elem
matching the given CSS selector.
Here we look for all <li>
elements that are last children:
Setting value of input field
Events
An event is a signal that something has happened. All DOM nodes generate such signals (but events are not limited to DOM).
Here’s a list of the most useful DOM events:
click
– when the mouse clicks on an element (touchscreen devices generate it on a tap).keydown
andkeyup
– when a keyboard key is pressed and released.DOMContentLoaded
– when the HTML is loaded and processed, DOM is fully built.
Handle button click:
Do a demo using button click to change the webpage:
Assesment:
Get to update login page to add js file
In js file update login button click to validate input to ensure email contains ...
Clarify this is not how logins work as can see correct answer in code
Last updated