Interacting with the DOM in JS, the Basics

George Treviranus
4 min readSep 15, 2019

Here’s a quick run-down of simple but easy methods to manipulate a web page using vanilla JavaScript. There are many more which are clearly outlined on pages like You May Not Need jQuery, but this should serve as a nice starting point on methods you are likely to use day-to-day.

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-element syntax, or with attributes using [my-element] syntax. Returns null if 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 elementsList is your NodeList, to iterate over your elements using methods like map and filter.

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")

Read more about querySelector and querySelectorAll.

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.

Notes: innerText is not the same as textContent, although it’s easy to confuse them. The latter returns all text, including hidden text, text within style and 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 .innerHTML).

Read more about innerHTML and innerText.

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 if block.
  • element.classList.contains("class-name"): Returns true or 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.

Read more here.

Change an element’s attributes

  • element.getAttribute("some-attribute"): Returns a string value for the attribute; returns null if 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 force parameter, which if it evaluates to false, doesn’t toggle the attribute.
  • element.hasAttribute("some-attribute"): Returns true or false, indicating the presence of the attribute, regardless of value.

Read more about getAttribute, setAttribute, removeAttribute, hasAttribute, toggleAttribute, and hasAttribute.

Change element’s inline CSS properties

  • element.style[propertyName]: Return the current value of a property. Replace propertyName with properties like width, borderWidth, or any CSS property converted to camelCase.
  • element.style[propertyName] = value: Set a given property name to a specified value as a string. Setting a number value requires a valid CSS unit.

Read more here.

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 object only.
  • window.scrollX: Same as window.scrollY, but from the left of the viewport.

Bonus: You can use element.scrollTop and element.scrollLeft to get the scroll distance within a scrollable element/container. They both return a number literal, just like scrollX and scrollY

Read more about scrollY and scrollX.

Get an element’s dimensions or relative position in the viewport

  • Math.round(element.getBoundingClientRect()[dimension]): Returns an element’s dimension ( width or height) as a number literal.
  • Math.round(element.getBoundingClientRect()[position]): Returns an element’s relative position (left, right, top, or bottom) from the edge of the viewport.

Notes: getBoundingClientRect is a very versatile built-in function with great support. The only instance methods not supported are x and 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", ""))

Read more about getBoundingClientRect and getComputedStyle.

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.

--

--