How to Select and Manipulate DOM Elements

John Au-Yeung
Level Up Coding
Published in
6 min readJan 22, 2020

--

Photo by Toa Heftiba on Unsplash

To make our web pages dynamic, we have to manipulate the elements on the page so that we can get the dynamic effects. The web browser’s standard library allows us to do this. There are multiple methods in the document object, which is the object which represents the items on our page. It has the whole DOM tree with all the elements we can get and then manipulate. In this article, we’ll look at a few methods to get elements from the page.

getElementsByClassName

The document.getElementsByClassName method lets us get a list of DOM objects on the page by their class name. Whatever object that has the given class will be returned by this method. It takes one argument which is a string with one or more class names separated by a space. It’s a method that’s part of any DOM element, which means it can also be called on elements that are returned by this method.

A NodeList object is returned, which is an array-like object. It has a length property and can be looped through by a for loop or a for...of loop, but array methods like forEach aren’t included in this object.

The simplest example would be getting the elements from the following HTML:

<p class='foo'>
foo
</p>
<p class='foo'>
bar
</p>

--

--