Interacting with the DOM in JS, the Basics
Mandatory “smash that like button and subscribe” if you find this helpful. 😉
Get an element
document.querySelector(".my-element"): Returns an element instance to use other built-in methods against. Query with IDs using
#my-elementsyntax, or with attributes using
nullif nothing is found.
document.querySelectorAll(".my-element"): Same as
querySelector, but returns a NodeList (a live collection of elements, which behaves more or less like an array). Access an individual element using the array-like index syntax, or convert the NodeList to an array using
Array.apply(null, elementsList), where
elementsListis your NodeList, to iterate over your elements using methods like
Bonus: you can replace
document with another element instance to further scope the search of your query. For example:
// get a parent element
const firstElement = document.querySelector(".cool-element-one")// get an element within the parent element, ignoring rest of DOM
const secondElement = firstElement.querySelector(".cool-element-two")
Get an element’s inner HTML or text
element.innerHTML: Returns a string representing the current state of that element’s inner HTML content, including tags, attributes, and text.
element.innerHTML = value: Sets the inner HTML of an element to the given
value. It must be proper HTML.
element.innerText: Returns a string representing human-readable text within an element, including descendants.
element.innerText = value: Sets the inner text of an element to the given
value. It can be any text, including special characters or even html, and will be rendered as a string exactly as given.
innerText is not the same as
textContent, although it’s easy to confuse them. The latter returns all text, including hidden text, text within
script tags, and the like.
textContent is useful when cloning nodes or sanitizing information (e.g., insert some unsafe content into a dummy element, then retrieve it using
Change an element’s classes
element.classList.add("class-name"): Add extra classes as parameters to add multiple classes.
element.classList.remove("class-name"): Same syntax as above, but removed the class.
element.classList.toggle("class-name", force): Toggles a class on an element. Accepts a second and optional parameter, which if it evaluates to false, doesn’t toggle the class. Useful for conditionally toggling the class without an
false, indicating the presence of the class.
element.classList.replace("old-class-name", "new-class-name"): replaces a given class on an element. If the class you want to replace isn’t present, the new class is added.
Change an element’s attributes
element.getAttribute("some-attribute"): Returns a
stringvalue for the attribute; returns
nullif the attribute doesn’t exists.
element.setAttribute("some-attribute", "some-value"): Sets an attribute on an element with the specified value. Overwrites the existing attribute value if one exists.
element.removeAttribute("some-attribute"): Removes the specified attribute from an element.
element.toggleAttribute("some-attribute"): Toggles an attribute on an element. Sets the value to `null`. Accepts a second and optional
forceparameter, which if it evaluates to
false, doesn’t toggle the attribute.
false, indicating the presence of the attribute, regardless of value.
Change element’s inline CSS properties
element.style[propertyName]: Return the current value of a property. Replace
propertyNamewith properties like
borderWidth, or any CSS property converted to camelCase.
element.style[propertyName] = value: Set a given property name to a specified
valueas a string. Setting a number value requires a valid CSS unit.
Get the vertical or horizontal scroll distance in the viewport
window.scrollY: Returns a read-only number representing the distance from the top of the page to the top of the current scroll position. This is a method on the
window.scrollX: Same as
window.scrollY, but from the left of the viewport.
Bonus: You can use
element.scrollLeft to get the scroll distance within a scrollable element/container. They both return a number literal, just like scrollX and scrollY
Get an element’s dimensions or relative position in the viewport
Math.round(element.getBoundingClientRect()[dimension]): Returns an element’s dimension (
height) as a number literal.
Math.round(element.getBoundingClientRect()[position]): Returns an element’s relative position (
bottom) from the edge of the viewport.
getBoundingClientRect is a very versatile built-in function with great support. The only instance methods not supported are
y, and that’s in IE (of course).
Alternative: You can also use
window.getComputedStyle in conjunction with
parseFloat to calculate an element’s height or width value as calculated from CSS. Here is an example of that:
const height = parseFloat(getComputedStyle(element, null).height.replace("px", ""))const width = parseFloat(getComputedStyle(element, null).width.replace("px", ""))
I wish someone had given me a guide like this a few years ago when I started to move away from jQuery; just a quick run down of some of the more common methods. Perhaps I’ll write a part two later with some lesser known, but still useful helper methods.
Please give me a shout on twitter if you found this helpful!
George is a front-end developer and digital designer living in Oakland, California. He is currently between jobs, about to start at ServiceNow on their Design Systems team. Other times, he can be found long boarding, playing video games, or collecting way too many Pokemon cards.