document // represents the HTML Document as objects that can be modified by JavaScript
Finding HTML Elements:
document.getElementById(id); // match id attribute
document.getElementsByTagName(name); // match tag name
document.getElementsByClassName(name); // match elements using class attribute
document.getElementsByName(name); // match all elements with the given name attribute
document.querySelector(p.intro); // match first element using CSS selectors
document.querySelectorAll(p.intro); // match all elements using CSS selectors
let navLinks = document.querySelectorAll('nav a'); // another example using css descendant selector with TagNames
document.forms["frm1"]; // using object and index
elements.matches(css selectors); // returns true or false if element(s) matches, useful to filter out certain elements
The following HTML objects (and object collections) are also accessible:
document.anchors
document.body // <body>
document.documentElement // <html>
document.embeds
document.forms
document.head // <head>
document.images
document.links
document.scripts
document.title
With the HTML DOM, JavaScript is able to access and change the elements of an HTML document.
For all nodes:
elem.parentNode // returns the parent of specified node
elem.childNodes // returns an array (NodeList) of children of specified node
elem.firstChild // returns first child
elem.lastChild // returns last child
elem.previousSibling // returns the previous node
elem.nextSibling // returns the next node
For element nodes only:
elem.parentElement // returns the parent
elem.children // returns an array (HTMLLiveCollection) of children elements
elem.firstElementChild // returns an element's first child
elem.lastElementChild // returns an element's last child
elem.previousElementSibling // returns element's previous element
elem.nextElementSibling // returns element's next element
Nodes are building blocks in the DOM, objects, basically everything in the DOM is a node.
Coordinates:
positioned: fixed; // relative to window
clientX // from left side of document
clientY // from top side of document
positioned: absolute; relative to document
pageX // from left side of document
pageY // from top side of document
Getting an element's coordinates:
elem.getBoundingClientRect() // returns information about size and position of an element relative to the viewport
x : 113.5 // absolute distance from left edge of viewport
y : 50 // absolute distance from top edge of viewport
width : 440 // width size of element
height : 240 // height size of element
top : 50 // Y coordinate, distance from top element edge and viewport, y
right : 553.5 // X coordinate, right element edge x + width
bottom : 290 // Y coordinate, bottom element edge y + height
left : 113.5 // X coordinate, left element edge, x
Example:
let coords = elem.getBoundingClientRect();
div.style.left = coords.left + "px";
div.style.top = coords.bottom + "px";
To move elements around using the DOM.
elem.innerHTML; // gets or sets the HTML markup inside an element
elem.outerHTML // gets or sets HTML markup and HTML tag, replacing whole element
elem.textContent // access text inside element, safer to use if only text
elem.hidden = true // global attributes or any other attribute
elemInput.value // access values from inputs
elemInput.checked // access boolean value from checkboxes
elem.href // access href attribute on anchor tags
elem.id // access the id attribute
elem.name // access the name attribute
elem.type // access the type attribute from form inputs
Once HTML elements have been selected and accessed, can change the content of those elements.
elem.hasAttribute(name); // check for existence returns boolean
elem.getAttribute(name); // get attribute value
elem.setAttribute(name, value); // to change or make an attribute if non-existent
elem.removeAttribute(name); // to remove an attribute
elem.attributes; // a collection of all attributes
(input.checked) // boolean attribute, true or false
elem.dataset.dataName // custom dataset attributes, start with data-, data-dataName=""
imageSaved.src = "newPic.jpg"; // can also use the names of the attributes
To change and access attributes on HTML elements.
Size properties:
offsetParent // reference to the element which is the closest positioned ancestor (parent) element
offsetLeft // provides x coordinates relative to offsetParent upper-left corner (left: ;)
offsetTop // providess y coordinates relative to offsetParent upper-left corner (top: ;)
offsetWidth // outer width of the element, full width of element including borders
offsetHeight // outer height of the element, full height of element including borders
clientLeft // measures left border width
clientTop // measures top border width
clientWidth // content width inside borders, doesn't include scrollbar
clientHeight // content height both account paddings
scrollWidth // like clientWidth but also include the scrolled out (hidden) parts
scrollHeight // like clientHeight but also include the scrolled out (hidden) parts
element.style.height = `${element.scrollHeight}px`; // expand the element to the full content height
scrollLeft // the width of the hidden, scrolled out part of the element
scrollTop // the height of the hidden, scrolled out part of the element
Window Sizes and Scrolling:
document.documentElement.clientWidth; // width of the window, doesn't count scrollbar like window.innerWidth
document.documentElement.clientHeight; // height of the window
Get the current Scroll:
pageXOffset // function getPos(){alert(window.pageXOffset)} - use to get pixels scrolled from left
pageYOffset // function getPos(){alert(window.pageYOffset)} - use to get pixels scrolled from top
Scroll into View:
elem.scrollIntoView() // makes an element visible on the top of the window
elem.scrollIntoView(false) // make element appear at the bottom
Forbid scrolling
document.body.style.overflow = "hidden"; // make a page unscrollable
document.body.style.overflow = ‘’; // reset it
To access scrolling and size information.
Styles:
elem.style.propertyName = "value"; // to target a style property
elem.style.display = "none"; // an example, link shows css properties
elem.style.backgroundColor = "#222"; // with multi word properties, background-color: #222;
Classes:
elem.className; // represents the class attribute
elem.classList; // an object representing class attributes
elem.classList.add("className"); // add a class
elem.classList.remove("className"); // removes a class
elem.classList.toggle("className"); // adds class if non-existent, otherwise removes it
elem.classList.contains("class"); // returns true if class exist, otherwise false
elem.classList.replace("oldClass", "newClass"); // to replace a class
Resets:
elem.style.property = ""; // to reset a property
elem.style.removeProperty("style property"); // to remove a property
CSS Text Inline Styling:
elem.style.cssText = `color: red !important;
background-color: yellow;
font-size: '16px;'`;
Use classes to dynamically style with JavaScript.
document.createElement(tag); // create a HTML element in JS, "div" = <div></div>
document.createTextNode(text); // create new text node in element, "text here" added
node.remove(); // removes an element from DOM
Insertion Methods:
node.append(); // adds after the last child
node.prepend(); // adds before the first child
node.before(); // adds before the element
node.after(); // adds after the element
node.replaceWith(); // replaces entire element
Insert AdjacentHTML Methods:
elem.insertAdjacentHTML(position, html) // parses text as HTML for HTML to be added
Example Inside an Event Handler:
elem.insertAdjacentHTML(
"afterbegin",
`<li>${input.value}</li>`
)
elem.insertAdjacentText(position, text) // passes text as Text
elem.insertAdjacentElement(position, element) // inserts an element
Position Values:
"beforebegin" // inserts before element
"afterbegin" // inserts html inside, at the beginning
"beforeend" // insert html inside, at the end
"afterend" // inserts html after element
Cloning Elements:
elem.cloneNode(true); // copies element with all attributes, text, and child elements
elem.cloneNode(false); // copies only the one element without subtree
To add and create elements inside a DOM.