DOManipulation!
Goals:
- Use native JavaScript from within HTML script tags to navigate and manipulate web pages via the Document Object Model (DOM).
Coding Snippets:
- Code in script tags must be JavaScript, not CoffeeScript, so remember to include all parentheses and semicolons. Also, new variables should be declared, e.g.,
let x = 5;
Math and Computer Concepts:
- The DOM is a structured representation of the currently-rendered web page. Browsers create the DOM for their own internal purposes, such as page rendering. Browsers also make the DOM accessible to other programs, permitting these to interact with the page. Access the DOM in JavaScript programs via the built-in
document
object. - Use the
document
object'squerySelector
andcreateElement
methods to gain access to existing page elements and create new page elements, respectively. The returned values are JavaScript element objects. Element objects have many properties and methods of their own, as illustrated above.
- There are often multiple ways to accomplish any given DOM-manipulation task using JavaScript. For example, the snippet above illustrates two ways to modify page elements' CSS properties.
- For more complicated scripts, you may elect to code in CoffeeScript and
compile
your program to JavaScript. A convenient online compiler is provided at coffeescript.org/#try.
Activities:
Save each of the following in a folder called .
- Write an HTML document called JustAScript.html that has only one HTML tag in the document body: script. Using JavaScript—in particular element object methods such as
createElement
andappend
—create an attractive web page describing your pet, favorite drink, or some other topic of interest. DelayedElements.html: create an HTML document that includes a script that calls the
setTimeout
function to add some additional page elements after a few seconds.Shuffler.html: Write an HTML document that contains a list of four or more items. Include a script that makes the browser render the items in an order different order than appears in the source file.
Use the
document
object'squerySelectorAll
method to get references to the list items. This method returns a special array-like collection of matching elements called aNodeList
. Convert this collection to an actual array before accessing elements, which you can do using theArray.from
method. Separately, be aware that therandom
function must be referenced asMath.random()
, and that it only has one usage: returning a real number in the range [0,1). You will likely have to manipulate the output to get random integer values.