Selecting Web Elements with Javascript using Query Selector, getElementsBy, and Dot Notation

Andrew Stahl
8 min readMay 31, 2022

--

If you’re looking for a comprehensive guide on selecting elements on a website using JavaScript, look no further!

Today’s topic: query selectors, getElementsBy, and dot notation

Agenda

  • Discuss a breakdown of why JavaScript is a necessary component for interactive web pages
  • Outline of a basic HTML page that we can use for testing our functions
  • Set up JavaScript to load properly before getting started
  • Review the different element selectors at your disposal for JavaScript

Background

Web development can seem like a daunting task at first, but luckily the roadmap is pretty well laid out. It is broken down into the three parts that are the primary languages of the web: HTML, CSS, and Javascript. For a very basic website, you would only need HTML. For a site where you want to have more efficient and scalable styling, you would add CSS. For a site that you would want the user to interact with the site (which could also change the structure of the site entirely), you would add Javascript. The latter is where we will focus our attention today.

When you’re writing JavaScript code for a website to make the website more interactive, you need to help JavaScript find specific parts of the web page and tie an action to those elements. We refer to this action as an “event listener”, and we will cover that more in-depth in another post. For now, we are going to dive into how we can point JavaScript towards specific elements on the page using three main methods: querySelector, getElementsBy, and dot notation.

Getting Started with HTML

Let’s start ourselves off with a basic HTML website that just has a title and a form where a user can enter in their first and last name:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>JavaScript Testing</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script type="text/javascript" defer src="index.js"></script>
</head>
<body>
<h1>Selecting Elements</h1>
<form id="name_form">
<label for="first_name">First name:</label>
<input type="text" id="first_name" name="first_name" class="name_box">
<label for="last_name">Last name:</label>
<input type="text" id="last_name" name="last_name" class="name_box">
<label for="submit">Submit</label>
<button id="submit" name="submit">Submit</button>
</form>
</body>
</html>

Here is a quick break-down of the code and elements that we’re seeing above:

  • A link to a CSS page for some styling
  • Script tag linking to “index.js” (with all of our JavaScript code) with a “defer” keyword (more on that in a moment)
  • A header tag
  • A form with the id “name_form” that has the following elements:
    - Text input field with the id “first_name” and the class “name_box”
    - Text input field with the id “last_name” and the class “name_box”
    - Submit button with the id “submit

That basic page is enough for us to start tackling the ways we can grab the elements on the website and add some interactivity to them.

Coding with JavaScript

Properly Loading the JavaScript Code

You noticed in the HTML code that I have a “defer” keyword on the script for the JavaScript. We need to be intentional about when our JavaScript kicks in when the page loads. Even though JavaScript is going to load alongside the HTML, it will load quicker than the HTML elements on the page. That means that it won’t pick up what we need it to do because what it’s looking at doesn’t exist yet.

For example, if I wanted to just log one of the elements on the page in the console and the JavaScript loads before the rest of the page, we’ll get a null result.

Picture of the console after an element is selected with a “null” result
Picture of the console after an element is selected with a “null” result

But, if we have the JavaScript load correctly, we’ll get the element logged in the console.

Picture of the console after an element is selected with the correct result
Picture of the console after an element is selected with the proper result

Here are three ways you can make sure that the JavaScript is loading only after the HTML page has been parsed:

  1. Adding a “defer” keyword to the script tag in the HTML code
  2. Putting the script for JavaScript at the very end of the HTML code (right before the closing body tag)
  3. Adding in an event listener on “DOMContentLoaded” in the JavaScript code before the rest of the code

Now that we make sure that our JavaScript is going to load when it needs to, let’s get into how to select elements.

Query Selectors

The first option that we’re going to look at to select an element on the page is a Query Selector. We can use these to return one or multiple element(s) from the page. There are two types of query selectors: querySelector() and querySelectorAll().

If you are using the querySelector(), this will return the first element that matches the parameter we pass into it. This is usually best for searching element IDs since IDs are not repeated amongst different elements. For example, in our JavaScript file, we might want to select the ‘first name’ element on the page. We can select it on the page by using the following syntax:

// Use the "#" to tell JavaScript to look at element IDs
const firstName = document.querySelector("#first_name")

Remember — this will only return the first element that it finds on the page.

If you are using the querySelectorAll(), this will return a NodeList of the elements that match the parameters we pass into it. This is usually best for searching classes or tags. For example, we can select elements in the class for “name_box” using the following syntax:

// Use the "." to tell JavaScript to look at element class names
const nameBoxes = document.querySelectorAll(".name_box")

This would be the result if you tried to console log the elements from above:

Picture of the console after elements are called with querySelectorAll, which produces a node list
Picture of the console after elements are called with querySelectorAll, which produces a NodeList

You can also use querySelectorAll to select all elements of a specific tag:

const inputBoxes = document.querySelectorAll("input")

Since querySelectorAll() will pull in a NodeList, you will not be able to iterate over this list the same way you might iterate over an array in JavaScript (i.e. utilizing a forEach function). You can get around this by calling on the Array.from() prototype.

const nameBoxesArray = Array.from(document.querySelectorAll(".name_box"))

Here would be the resulting console log:

Picture of the console after we create an array from a nodeList
Picture of the console after we create an array from a NodeList

There are more complex ways to grab elements on the page. Take a look at Mozilla’s MDN page on querySelector or querySelectorAll.

getElementsBy

Similarly to query selectors, you can use “getElementsBy” for selecting elements on the page. The syntax is only slightly different.

If you want to select elements by their ID, you can use the “getElementById” method:

const firstName = document.getElementById("first_name")

Notice — you don’t have to use the “#” in front of the element ID “first_name” since you’re already designating that we’re looking for IDs. Query selectors are more general so you would need to specify the attribute (ID, class, etc.) in the parameter.

If you want to select elements by their class, you can use the “getElementsByClassName” method. This will produce an HTMLCollection return value.

const nameBoxes = document.getElementsByClassName("name_box");// If you want to get the first element on this list
const firstNameBox = nameBoxes[0];

Note — we’re adding an “S” at the end of “Element” because this will return multiple elements. And here is the result in the console log:

Picture of the console after elements are called with getElementsByClassName, which produces an HTMLCollection
Picture of the console after elements are called with getElementsByClassName, which produces an HTMLCollection

You can also search by tag name, whether you’re looking for “p” tags, “div” tags, etc.

const inputBoxes = document.getElementsByTagName("input")

You can even get very specific with these elements by chaining these methods together. Recall that the name form in the HTML page has the ID “name_form”. So, we can also grab all of the boxes in the form using their class of “name_box” with this syntax:

const inputBoxes = document.getElementById("name_form").getElementsByClassName("name_box")

Remember — you need to strike a balance between the readability, succinctness, and memory-allocation of your code. Choose your paths wisely!

Dot Notation

The final area that we’ll look at today requires dot notation. We’ve seen this in other areas of JavaScript as well, such as when you’re trying to retrieve a value from an object. With this method, we’ll be able to use the IDs within a parent element to collect data or perform actions on a child element.

Let’s say as an example that we want to grab the name form because we have code that needs to see what the user entered into the “First Name” box. We can start with declaring a variable that grabs this from the page (below I’m using query selector, but you can also use getElementsBy…)

const nameForm = document.querySelector("#name_form");

Then, if we want to collect the first name input box and see what value was entered, we can use the following line of code:

// Remember, the first name input field has an ID of "first_name"
const firstName = nameForm.first_name.value;

I ran the webpage and opened up the console. This is what it looks like if I wanted to log that value:

Picture of the console after elements are called with dot notation
Picture of the console after elements are called with dot notation

Maybe you have code that allows you to store these values in an object. You might not want to save the first and last name in separate variables, so you can use dot notation to simplify:

const nameObj = {
firstName: nameForm.first_name.value,
lastName: nameForm.last_name.value
}

Look how much simpler that becomes!

IMPORTANT — if you are using dot notation, you will need to make sure that the IDs you use don’t have a dash in them. The reason is that JavaScript does not recognize dashes as valid characters in variable names. If you are creating an HTML page, having IDs with underscores instead of dashes would be best if you need to pull that data with JavaScript. If you’re pulling from another site, you’ll have no choice but to work with whatever naming convention they have in place (and therefore will need to use query selectors or getElementsBy to select your data).

Wrapping Up

So there you have it! A few different ways that you can use JavaScript to select elements on your page. I hope this has given you a good overview of some essential tools for web development.

Happy Coding!

--

--

Andrew Stahl

Passionate Software Developer, Adventurous Explorer, and Avid Movie Quoter