Getting Elements in Javascript

A monitor with colorful code on the screen.

In Web Development, we commonly need to grab HTML elements in order to manipulate them with Javascript.

So how do we accomplish this?

With the getElementBy method of course!

It’s a pretty simple, but truly important, aspect of Javascript. And in this blog, I’ll show you how simple it is.

When you’re wanting to grab an element from your HTML, you’ll first need to declare a variable.

For an example let’s haveb a specific heading from our HTML.

<h1 id="first heading" class="headers">Heading</h1>

Now, we want to do something with this heading in Javascript (let’s say make the text bigger when you click on it or whatever). Before we can do anything though we have to grab it.

First we create a new variable, which we’ll call headerOne.

let headerOne

Then we’ll assign to it a method, which is the getElementById method.

let headerOne = document.getElementById()

There you can see the method, which is the same everytime, which allows us to grab elements by using their ID name to find them, but we haven’t yet put in the ID name, so this method does nothing. You’ll see that there’s empty brackets at the end of the method. It’s in between these brackets that we put the string that is assigned as the element’s ID, which, in this case, is “first heading”.

let headerOne = document.getElementById("first heading")

And there you have it! The headerOne variable now “has” the HTML element we wanted. We can now manipulate this element with Javascript however we want.

There are a few other ways by which you can grab elements. I’ll list them here.

getElementsByClassName()

This one allows you to get any element(s) with a specified class name. Using our above example, if we put "headers" in between the brackets, we would get the element we wanted, but we would also grab everything else that had the same class name, which we didn’t want to do, but in another situation we might.

getElementsByTagName()

This allows you to get any element(s) with a specified HTML tag. So you could grab every thing with a <p> tag, <h3> tag, <div> tag, etc.

And that’s mostly it! See? Pretty simple, now get out there and start grabbing your elements!