You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
have special properties and methods to interact with the elements
have available methods and properties depend on the kind of element
can be selected in various different ways (via JavaScript)
can be created and removed via JavaScript
Querying the DOM
querySelector(), getElementById():
return direct object reference to DOM element
return single element
different ways of querying elements (by CSS selector, by ID)
querySelectorAll(), getElementsByTagName():
querySelectorAll() returns a non-live (static) NodeList, getXByY returns live NodeList
return collections of elements (array-like objects) -> NodeList
different ways of querying elements (by CSS selector, by tag name, by CSS class)
document.body => selects the <body> element node.
document.head => selects the <head> element node.
document.Element => selects the <html> element node
Element.closest('CSSselector') => traverses the element and its parents (heading toward the document root) until it finds a node that matches the specified CSS selector.
Element.previousElementSibling, Element.nextElementSibling: read-only property returns the Element immediately prior or after to the specified one in its parent's children list, or null if the specified element is the first one in the list.
Live Node Lists vs Static Node Lists
live means that changes in DOM are reflected in the collection
static means that only a snapshot of the current state is taken
use e.g. getElementsByTagName() instead of querySelectorAll() if you want to have a live connection
Attributes vs Properties
Traversing the DOM
child, descendant, parent, ancestor
Styling DOM elements
Creating and Inserting Elements
Element.insertAdjacentHTML(position, text): parses the specified text as HTML or XML and inserts the resulting nodes into the DOM tree at a specified position.
Recommended: instead of innerHTML method that replaces whole content between selected HTML tags and forces browser to re-render whole block
document.createElement(): creates the HTML element specified by tagName
Node.appendChild(CREATED_OR_EXISTING_ELEMENT): adds node to end of list of children of a specified parent node. If given child is a reference to an existing node in the document, appendChild() moves it from its current position to the new position (-> since you are holding only a reference to the element object).
Element.append() / Element.prepend(): inserts a set of Node objects or string objects a) after the last child OR b) before the first child of the Element. String objects are inserted as equivalent Text nodes.
Node.cloneNode(deep): returns a duplicate of the node on which this method was called. deep controls if the subtree contained in a node is also cloned (-> true) or not (-> false).
Attaching Data to DOM elements
use data-... attributes to attach data to a DOM element
to get or set data of DOM element use dataset property of DOM element
[1] name is converted to camel case
[2]
// HTML: <div id='test' data-test-info="foo"></div>constel=document.getElementById('test');// get dataconst{ testInfo }=el.dataset;// "foo"// set datael.dataset.someInfo="bar"// New HTML: <div id='test' data-test-info="foo" data-some-info="bar"></div>
Getting Element Box Dimensions
// HTML: <div id='test' data-test-info="foo"></div>constpositionObj=el.getBoundingClientRect();// returns object with position dataconst{ bottom, top, height, width, left, right, x, y }=positionObj;el.offsetTop;// outer space between end of box to top of documentel.clientTop;// space of border and scrollbarel.clientWidth;// space of box without border and scrollbarel.offsetHeight;// visible height of boxel.scrollHeight;// entire height of box including space than can be reached by scrollingel.scrollTop;// space to top of box content at the current scroll positionwindow.innerWidth// current browser width including scrollbardocument.documentElement.clientWidth;// current browser WITHOUT scrollbarel.scrollTo(x,y);// scroll to certain positionel.scrollTo({top: x,behavior: 'smooth'});// scroll to certain position with smooth transitionel.scrollBy(x,y);// if called multiple times, continues to scroll with defined valuesel.scrollIntoView({behavior: 'smooth'});// scroll element into view with smooth transition
DOM Elements and Inheritance
Example below: every HTMLInputElement has access to all properties of HTMLElement, Element, Node and EventTarget (-> prototype chain) and its own properties that are specific to HTMLInputElement
Using HTML Template Element
<template> can hold some content that will be hidden when the page loads
use JavaScript to pull content out and display it where you like
<templateid="foo"><h2>Hello</h2></template>
constel=document.getElementById('foo');constelBody=document.importNode(el.content,true);// do a deep (-> true) import of all the content of the elementbody.append(elBody);
Loading Scripts Dynamically
use case: you have a script file that you want to be loaded only at a certain time
constsomeScript=document.createElement('script');someScript.textContent='alert("foo");';document.head.append(someScript);conststartAnalytics=()=>{constanalyticsScript=document.createElement('script');analyticsScript.src='assets/scripts/analytics.js',// OR URL pathanalyticsScript.defer=true;document.head.append(analyticsScript);// is directly loaded when appended};