How to Use $ in JavaScript without JQuery
I remember the days of jQuery, when we could use $
to target anything in the DOM.
In JavaScript, I do find myself using document.querySelector()
quite often, which functions very similarly to jQuery’s $
.
Luckily, we can bind $
to document.querySelector()
.
const $ = document.querySelector.bind(document);
const $$ = document.querySelectorAll.bind(document);
Let’s see what we can do with $
, or document.querySelector()
, which only selects first matching element.
$('.text').style.color = "#fff";
$('#text').innerHTML = "Hello!";
What about $$
, or document.querySelectorAll()
, which returns a NodeList of all matching elements?
$$('img').forEach(img => console.log(img.src));
This functionality is actually already available in Chrome’s DevTools without the need to manually bind $
or $$
to document.querySelector()
or document.querySelectorAll()
, respectively.