Skip to content
Home » Blog » 5 Important Javascript Selectors you need to know

5 Important Javascript Selectors you need to know

Javascript Selectors

If you’re reading this article, you should be familiar with basic javascript syntax and the DOM(Document Object Model), and some HTML/CSS. Well, that’s pretty much everything you need to know to understand javascript selectors, once you’re ready, let’s dive in!

WHAT ARE Javascript Selectors?

DOM Selectors or Javascript selectors are used to select elements inside the HTML Document using plain javascript.

In this article, we are gonna take a look at 5 types of selectors

  1. querySelector()
  2. querySelectorAll()
  3. getElementsByTagName()
  4. getElementsByClassName()
  5. getElementById()

HTML PAGE

Let’s create an HTML document that we’ll be using for testing each of the selectors

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Selectors</title>
    <style>
        div{
            background-color: aliceblue;
            margin: 20px;
        }
    </style>
</head>
<body>
    <div class="query">
        class="query"
    </div>
    <div class="query-all">
        class="query-all"
    </div>
    <div id="id-name">
        id="id-name"
    </div>
    <div class="class-name">
        class="class-name"
    </div>

</body>
</html>

And, when we run it, a page like this pops up

Great! Now that we’ve created our HTML document, let’s use some javascript selectors in the console!

querySelector

The querySelector() function returns the first element that matches the CSS Selector from the document. In order to specify class and id, we use “.” and “#” before the CSS Selector name, for instance

document.querySelector(".query")

This selects the first div with class name query

document.querySelector("#id-name")

This selects the third div, with id name as id-name

document.querySelector("div")

Here, we’re using the tag name, div, and since there are 4 different divs in the document, the first one is selected, that is, the one with the class name query

querySelectorAll

querySelectorAll() is very similar to querySelector, except for the fact that it returns an array of all the elements that have the same CSS Selector. If we run…

document.querySelector("div")
Javascript Selectors

As we can see, we get all 4 div inside an array, which we can through array indexing

divs = document.querySelectorAll("div")
console.log(divs[2])
Javascript Selectors
Note

For querySelector() and querySelectorAll(), you have to specify “#” or “.” before the CSS selector name, which otherwise would throw an error

getElementsByTagName

getElementsByTagName() returns an array of all elements that matches the tag name entered

document.getElementsByTagName("div")
Javascript Selectors

Here, it returns an array that includes all the div elements, which can be accessed using array indexing, for instance, to select the second div we use document.getElementsByTagName("div")[1]

getElementsByClassName()

getElementsByClassName() returns an array of all elements with the same class name as entered. But unlike the querySelector(), we don’t have to enter “.” before putting in the class name into the function

document.getElementsByClassName("query")
Javascript Selectors

It returns an array that includes all the elements with the class name “query”, that is, only the first div element, which can be accessed using array indexing. For instance, to select the second div we use document.getElementsByTagName("div")[1]

getElementById()

getElementById() function returns the first element that matches the id name from the document, ignoring the rest. It might seem really similar to the getElementsByTagName and getElementsByClassName, but, remember, unlike them, this selector returns only the first found element, and not an array.

document.getElementById("id-name")
Javascript Selectors

As we can see, we get back only one element, the third div. Since it is the first element with the id named “id-name”

Note

For getElementById() and getElementsByClassName() you don’t have to put in “#” and “.” before the id/class name

USING Javascript Selectors IN A PROGRAM

Let’s make a simple counting web application using javascript selectors, in which, we have an h1, that says 0, and a button that increases the number in h1 with consecutive clicks

HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Selectors</title>
    <script src="script.js" defer>
    </script>
</head>
<body>
    <h1>0</h1>
    <button>Count</button>
</body>
</html>
Javascript Selectors

Now that we’re are done with the HTML part, and that we’ve linked it to the javascript file, script.js. Let’s move on with the JavaScript code

JAVASCRIPT

let h1 = document.querySelector("h1")
let btn = document.querySelector("button")
var count = 0
btn.onclick = () => {
    count++;
    h1.innerHTML = count;
}

With this code, the count of the h1 should increase as we click the button

Explanation

We first create 2 variables, h1 and btn that stores the respective elements using the querySelector function.

After that we create a variable count that stores the value 0

Then, we create an onclick event for the button, and then assign it to a function.

This Function adds 1 to the value of count, and then assigns its value to the h1. And with that we’re done with an example code.

TO SUM UP . . .

We use different kinds of javascript selectors to select a particular element from the DOM and manipulate it. There are many other selectors, but we’ve only discussed 5 most important and frequently used ones, querySelector, querySelectorAll, getElementsByTagName, getElementsByClassName, getElementById

If you are on your way to becoming a Web developer, you might find our site really helpful. Hit this link for more JavaScript related posts
Check it out, it’s Simply the Best Code

Leave a Reply

Your email address will not be published. Required fields are marked *