Some additional notes:
.innerHTML
property is the content of the HTML element, changing this is a common way to display data in HTMLdocument.write()
writes to an HTML output, if used after an HTML document has loaded, will delete all existing HTML, e.g
Here, after the HTML document is loaded, the onclick will replace all existing HTML with 11.
window.alert()
writes into an alert box.
When the HTML document is loaded, a pop up window appears with the alert written on it, so for the above, 11.
- last is
console.log
, used for debugging, outputs to browser console - *NOTE: ** JS does not have any print methods
JS types are dynamic:
JS Objects are written as name value pairs:
In JS, it is common to declare objects with const
in front
In simple terms, HTML events are “things” that happen to HTML elements. When JS is used in HTML pages, JS can “react” on these events,
Often, when such HTML events are detected, we want to perform some sort of action on it. JS lets us execute code when events are detected.
HTML allows for event handler attributes, with JS code:
An example is onclick
attribute (with code) is added to a <button>
element:
There are countless events in HTML, some of the common ones are:
onchange
- HTML element as been changedonclick
onmouseover
- The user moves mouse over an HTML elementonmouseout
- The user moves mouse away from an HTML elementonkeydown
- The user pushes a keyboard keyonload
- The browser has finished loading the page
These are only a couple, and therea re actually many. Here’s a link to more: https://www.w3schools.com/jsref/dom_obj_event.asp
We’ll look more into these event handlers when we go over HTML DOM chapters
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
We can use ```replace()“ method to replace a specified value with another value in a string
- The replace() method does not change the string it is called on.
- The replace() method returns a new string.
- The replace() method replaces only the first match
let newText = text.replace(/Microsoft/g, "W3Schools");
replaces all instanceslet newText = text.replace(/Microsoft/i, "W3Schools");
replaces case insensitive
Theres a lot of things you can do with strings, here is the full reference from W3Schools: https://www.w3schools.com/jsref/jsref_obj_string.asp
The indexOf()
method returns the index of (the position of) the first occurrence of a specified text in a string:
The lastIndexOf()
method returns the index of the last occurrence of a specified text in a string:
Both indexOf()
, and lastIndexOf()
return -1 if the text is not found.
Can also pass a second parameter, which is the index to start the search from. indexOf()
starts from parameter to end, whereas lastIndexOx()
goes from parameter to the beginning.
To make a string with `
or "
in it, we write strins with back-tics, known as template literals:
HTML Templates: