DEV Community

Steven Frasica
Steven Frasica

Posted on

Finding DOM Elements

It's important to understand how the DOM works, and the next step is the ability to manipulate it and make changes to it. There are a variety of ways to go about this, but we'll discuss a few methods and techniques. First of all, we'll be using these methods to identify elements.

You can target an element by its id, provided it has one.

document.getElementById("first");

It is best practice to have unique ids for all of your tags, but if there are repeats, getElementById() will return the first tag only.

You can target a collection of elements all comprised of the same tag name.

document.getElementsByTagName("p");

This will provide you with a collection of nodes that are all p (paragraph) tags.

This time we'll set the collection to a variable to make it easier to access individual elements in the collection.

const paragraphs = document.getElementsByTagName("p");

Let's say there are multiple p tags on the page, and the variable paragraphs now represents the collection of the p tags. The collection is similar to an array, but not exactly an array. We can access a specific p tag using bracket notation. Let's do that and save it to a variable.

const secondP = paragraphs[1];

A reminder that the collection of nodes is zero-indexed like an array, so the second element will be denoted by [1].

<div id= "parent">
 <p> Hello from inside the p tag </p>
</div>

Above, the <p> tag would be considered a child of the <div> tag because it's inside the <div>. Let's access the <p> tag using our <div>.

const parentDiv = document.getElementById("parent");
const childP = parentDiv.firstChild;

//Output is <p>

Alternate way is to use bracket notation and childNodes. childNodes will return a collection of all the immediate children of the element, in this case the <div>.

const childP = parentDiv.childNodes[0];

Top comments (0)