DOM Manipulation
- DOM stands for Document Object Model. It is an API to access
represent the structure of a document:
- The DOM is not unique to JavaScript. Many programming languages implement the DOM.
- Thus, interacting with an .html document is similar in most languages. The
class names and method names should be familiar.
- Walk through rawDomNavigation
childNodes
is a NodeList
object (not an array)
- But,
NodeList
does have a forEach
method.
- the body’s first node is a text node containing the blank space between the
<body>
tag and the <h1>
tag.
- Everything is a
Node
, not just Elements (i.e., the stuff with tags)
#text
is a kind of node. So is #comment
- nodeType is an int. You have to look up the name of the type that goes with each int.
- Look at the
<ul>
to see the difference between textContent and innerHTML
- In JavaScript, you can access information by navigating through the DOM from the top;
but, we usually use one of three methods to grab the object(s) we are specifically
interested in.
- Notice the “number” of the noun.
getElementById
is singular. It returns a single object.
getElementsByClassName
is plural. It returns an HTMLCollection of objects.
HTMLCollection
s can be tricky:
- They mostly behave like arrays
- You can use
[]
notation to access elements
- They have a
length
method. But,
- They don’t have most (now) standard array methods like
forEach
and map
.
- However You can use
Array.from
to create an Array based on an HTMLCollection
- Be aware: an
HTMLCollection
is a “live” list: It will change as the DOM is updated, whereas
an Array is a “static” list: It will not be updated.
- Walk through basicDOMManipulation
- Walk through eventVsThis
- Note specifically:
- the difference between
function
and () =>
, and
- that the difference need not be relevant. Just use
li[i]
- Walk through placementOfScript.html