YDNjQ - Selectors

YDNjQ - Selectors

YDNjQ - "You Don't need jQuery" is a series of plain JavaScript snippets that will show you how much you can do without using any library and especially jQuery.

JavaScript is a very popular language but it used to have quite a bad reputation until recent years.

The web was dominated by libraries, or more precisely by a specific library - jQuery, but during the last years, JavaScript improved so much that most of the time you can do just fine by using only plain JavaScript.

In this post we are going to talk about selectors, or the Easy Peasy way we used to select elements via the $("element"), $(".class") and $("#id") using jQuery.

Given the following situation:

<div></div>
<div></div>
<div></div>

<div class="class"></div>
<div class="class"></div>
<div class="class"></div>

<div id="id"></div>

Selecting all the div elements on this document

jQuery way

$("div")

Plain JavaScript

document.getElementsByTagName("div")

Selecting all the div elements with ".class"

jQuery way

$(".class")

Plain JavaScript

document.getElementsByClassName("class")

Selecting the div element with the "#id"

jQuery way

$("#id")

Plain JavaScript

document.getElementById("id")

But what if we don't want to memorize all the variations based on the selectors that JavaScript seems to impose us to use?

We want to select something with only one simple way and maybe even the way we do it in CSS.

No fears Folks! We don't have to memorize all that and confuse various getElementsBySomethingSomething!

Here you go:

document.querySelectorAll("div")

document.querySelectorAll(".class")

document.querySelectorAll("#id")

document.querySelectorAll() is very smart, and returns a NodeList of elements selected by a given CSS selector.

Now, you're probably thinking:

What is an actual NodeList?

And if you have an eye for details you may have noticed that the previous .getElements selector methods returned something that is an HTMLCollection.

Well they are pretty similar, both are collections of DOM nodes, the only difference is that the first (NodeList) is a more general list that can include various node types, meanwhile the HTMLCollection will include only node elements like div, body, ul, etc.

So here it is, just a small step towards a cleaner, faster, and more maintainable code on the web.

I will write more about plain JavaScript and how powerful it alone can be, stay tuned!