- What is the DOM?
- Examining The Document Object
- DOM Selectors For Single Elements
- DOM Selectors For Multiple Elements
- Traversing The DOM
- Creating Elements
- Removing & Replacing Elements
- Event Listeners & The Event Object
- Mouse Events
- Keyboard & Input Events
- Event Bubbling & Delegation
- Local & Session Storage
The DOM is a structured representation of a HTML document.
- Document Object Model
- Tree of nodes/elements (tags) created by the browser
- JavaScript can be used to read/write/manipulate the DOM
- The DOM is Object Oriented Representation (each node has its own set of properties and methods)
The browser gives us a window object and inside that we have a document object. The diagram above represents the loaded documents web page.
- root element which is the
<html>
element - below we have the
<head>
and<body>
tag which are both siblings (i.e. on the same level) in the tree - in the
<head>
we have things like the meta tags, title etc. - in the
<body>
we have our output such as h1, HTML5 header/footer, links tags etc. - we can manipulate the elements using JavaScript
- you can use libraries such as jQuery to make it a little easier to manipulate the DOM, but it is worth learning how to do these stuff using vanilla JavaScript
Analogy: using jQuery to select elements from the DOM is kind of like using a sledge hammer to kill a mosquito.
document
object returns the HTML structure.
all
returns all of HTML document tags as arrays- uses zero indexing to call back specific tag from the document array
all.length
finds the length (properties) of the document array (i.e. number of elements in the DOM)head
returns the<head>
element of the current documentbody
returns the<body>
element of the current documentdoctype
returns the Document Type Declarationdomain
returns the domain nameURL
returns the document location as a stringcharacterSet
returns the character encoding of the documentcontentType
access to the content type i.e. text/html
forms
returns an all the<form>
elements contained in the document (if there are more forms they will have index numbers assigned to them)id
select ID of the formmethod
get method (forms have get and post methods)action
returns any action on the form
links
returns a collection of all links in a document with a value for the href attribute- we can access certain links using the index number
id
returns the link idclassName
returns a string of all the classeslinks[0].classList[0]
returns a DOMtokensList of the different classes (use zero index to select a specific class)
images
returns images, if none then returns an empty collectionscripts
returns a list of the<script>
elements in the documentgetAttribute()
returns the attribute of a script
By default, you cannot run loops on HTML collections. You must convert them into an array in order to use loops such as forEach
loops etc.
Array.from()
creates a new, shallow-copied Array instance from an array-like or iterable object
DOM Element Selectors are object methods that allow us to pull things from the DOM, manipulate and do different things to the elements or nodes.
Note: jQuery is useful for quick simple plugins and/or scripts for specific actions. You should no longer use it for DOM manipulation.
Two types of selectors:
- Single Element Selectors which allows you to grab a single element by its id/class/etc and it can only store one element. If you use a single element that appears more than once in the DOM, it will only grab the single first instance of the element
- Multiple Element Selectors will grab all the elements with the class and return a HTML collection or a node list depending on which selector you use
Two ways to select single elements:
document.getElementById()
returns an Element object representing the element whose id property matches the specified stringdocument.querySelector()
is newer and much more powerful that returns the first Element within the document that matches the specified selector, or group of selectors- if no matches are found,
null
is returned - works exactly like jQuery and accepts any CSS selectors
- if no matches are found,
Note: Target a specific element even if there is more than one in the DOM by using the CSS :first-child/:last-child/:nth-child() sudo element within the querySelector.
document.getElementByClassName()
returns an array-like object of all child elements which have all of the given class namesdocument.getElementByTagName()
returns an HTMLCollection of elements with the given tag namequerySelectorAll()
returns a static NodeList (not HTML Collection) representing a list of the document's elements that match the specified group of selectors- NodeList counts not just elements but also things like text nodes and it also allows us to do things such as forEach loops and other array methods without having to convert it into an array first
Note: for
loop will work with both HTML Collections and Node Lists (using length
on a HTML collection and access the item using the index) whereas the forEach
loop will only work with Array/NodeList and not with HTML Collections.
Traversing the DOM is the action of moving up and down the DOM object and dealing with specific parent and children nodes or whatever it is that we select.
There are different properties attached to the document items/nodes and it all depends on whether we select the parent or child of these nodes.
childNodes
returns a NodeList of child nodes of the given element, this includes text nodes which represents line breaks within HTML documentnodeName
returns the name of the current node as a stringnodeType
represents the type of the nodenodeType
will return a number for the node selected- 1 = Element
- 2 = Attribute (deprecated)
- 3 = Text node
- 8 = Comment
- 9 = Document itself
- 10 = Doctype
children
returns a HTMLCollection which contains all of the child elements of the node upon which it was calledfirstChild
returns the node's first child in the tree, or null if the node has no childrenfirstElementChild
returns the object's first child Element, ornull
if there are no child elementslastChild
returns the last child of the nodelastElementChild
returns the object's last child Element or null if there are no child elementschildElementCount
returns an unsigned long representing the number of child elements of the given elementparentNode
returns the parent of the specified node in the DOM treeparentElement
returns the DOM node's parent Element, ornull
if the node either has no parent, or its parent isn't a DOM ElementnextSibling
returns the node immediately following the specified one in their parent's childNodes, or returnsnull
if the specified node is the last child in the parent elementnextElementSibling
allows us to move down the DOM, from within the element node and we can combine this property to move multiple times downpreviousSibling
returns the node immediately preceding the specified one in its parent's childNodes list, ornull
if the specified node is the first in that listpreviousElementSibling
allows us to move up the DOM, from within the element node and we can combine this property to move back up the DOM
Note: We can combine nextElementSibling
and previousElementSibling
to move up and down the element node. Note we can all Traverse up and down Child Nodes using .nextSibling
and .previousSibling
(Child Nodes contain other nodes other than elements).
createElement()
creates the HTML element specified by tagName, or an HTMLUnknownElement if tagName isn't recognizedsetAttribute()
sets the value of an attribute on the specified elementappendChild()
adds a node to the end of the list of children of a specified parent nodecreateTextNode()
creates a new string to be put in the text node
- Create an element
- Add an id/classes/attributes to the element (Optional)
- Add text Node (& append to element)/innerHTML (Optional)
- Append the new element to the DOM as child element node.
- Step 1
- Create a element using a variable
- Add id/class/attributes/textNodes to the element
- Step 2
- Locate the old element we would want to replace and add it to a variable
- Get the parent element of the old element and store it in a variable.
.replaceChild()
requires a parent object to call on the method
- Step 3
- Replace the old element with the new element using the
.replaceChild()
- Replace the old element with the new element using the
- Step 1
- Create a variable to store all the elements using
querySelectorAll()
. - Create a variable to store the ul (parent) element of the li element.
- Create a variable to store all the elements using
- Step 2
There are two ways in which we can remove/delete a child element from the DOM.
- The first variable in step 1 allows us to select an element using the index, then followed by the
remove()
to remove the element - Alternatively we can use the second variable and remove by child element using the parent and calling on the
removeChild()
, then passing in the first variable with the index as the parameter/argument
- The first variable in step 1 allows us to select an element using the index, then followed by the
replaceChild()
replaces one child node of the specified node with anotherremove()
of the DOMTokenList interface removes the specified tokens from the list- will remove the object from the tree it belongs to
removeChild()
will remove a child node from the DOM. Returns removed nodeadd()
of DOMTokenList interface adds the given token to the listhasAttribute()
returns a Boolean value indicating whether the specified element has the specified attribute or notremoveAttribute()
removes the attribute with the specified name from the element.
Events listeners & the event object allows us to have interactivity on our web page. We can listen to Events on any elements in the DOM.
addEventListener()
sets up a function that will be called whenever the specified event is delivered to the target- usually takes in two parameters, E.g. '
click
' & named or unnamedfunction
- usually takes in two parameters, E.g. '
preventDefault()
tells the user agent that its default action should not be taken as it normally would be
- Step 1
- Query Select an element in the DOM we wish to listen to events on
- Step 2
- Add
.addEventListener()
to listen to the element, takes in two parameters- an event action, and
- a function
- the function can either be an unnamed function or a named function
- Add
All event objects are based on the Event
Object, and inherits all of it's properties and methods
target
returns the element that triggered the eventtype
returns a string containing the event's typetimeStamp
returns the time (in milliseconds) at which the event was createdclientY
&clientX
are property of theMouseEvent
interface returns the horizonal/vertical coordinate within the application's client area at which the event occurredoffsetX
&offsetY
are property of theMouseEvent
interface provides the offset in the X/Y coordinate of the mouse pointer between that event and the padding edge of the target node
MouseEvent represents events that occur due to the user interacting with a pointing device
click
is when button is pressed and released on a single elementdblclick
is when button is clicked twice on a single elementmousedown
is when button is pressed on an elementmouseup
is when button is released over an elementmouseenter
is when a pointing device is moved over the element that has the listener attachedmouseleave
is when the pointer is moved out of an element that has the listener attached to itmouseover
is when a pointing device is moved onto the element that has the listener attached or onto one of its childrenmouseout
is when is moved off the element that has the listener attached or off one of its childrenmousemove
is when pointing device is moved while over an element
KeyboardEvent describe a user interaction with the keyboard; each event describes a single interaction between the user and a key on the keyboard.
InputEvent interface represents an event notifying of editable content change.
keydown
produce a character value and for keys that do not produce a character valuekeyup
fired when a key is releasedkeypress
produces a character value is pressed downfocus
fired when an element has received focusblur
fired when an element has lost focuscut
fired when a selection has been removed from the document and added to the clipboardpaste
fired when a selection has been pasted from the clipboard to the documentinput
fired synchronously when the value of an<input>
,<select>
, or<textarea>
element is changed
submit
is fired when a form is submittedchange
is fired when selected list option is changed
Event Bubbling is the bubbling up of events through the DOM. When an event occurs in a particular element in the DOM, it will bubble up through its parent.
Event Delegation is almost quite the opposite of Event Bubbling. It is where we put the .addEventListener
on the parent element and use logic/condition on the Event Handler (function) to target the actual child element we would want the event action (e.g., click
) to be applied/targeted to.
We would use event delegation for situations such as deleting a specific/selected list item (if we do not use event delegation, the event will only apply to the first instance of the list element and not to the other list elements) or when we would want to dynamically insert something into the DOM through JavaScript for example if we insert a new list item that was not there originally when the page loaded, we would then require the use of event delegation.
localStorage
/sessionStorage
API is part of the browser window object- we can store key:value pairs into local/session storage, but the value must be a string
- we can also save arrays and objects by converting them into a string using
JSON.stringify()
- to pull the data out of storage we parse it back using the
JSON.parse()
localStorage
will stay until you manually clear it out in your settings or in your programsessionStorage
will go away when the browser is closed (i.e., session ends)
- key:value pairs are required when storing data
setItem()
will add the key to the storage, or update that key's value if it already existsgetItem()
will return the key's value or null if the key does not existremoveItem()
will remove the key from the storage if it existsclear()
will remove all the stored keys/items
JSON.stringify()
converts a JavaScript object or value into a JSON stringJSON.parse()
parses a JSON string and converts it into a JavaScript object