Vanilla JS. AddEventListener, querySelector and closest

List of some native Javascript functions to manipulate the DOM

Gerardo Fernández
5 min readOct 4, 2019

Today I have prepared a short article but that I found interesting to do, especially now that JQuery has ceased to be the library we installed as soon as we started developing the front of a website.

Basically what I want with this article is that you familiarize yourself, if you are not already, with 3 Javascript functions that allow us to solve the use cases we were so used to with JQuery. These are:

  • addEventListener, to handle the clicks on the elements of our application.
  • querySelector and querySelectorAll to select elements in the DOM (as we did at the time with$('selector').
  • closest to be able to select the closest parent element we have.

So, with that said, let’s see how to use them.

0. What are we going to do?

The idea of this article is going to be able to detect a click on an image and add a class to the element that contains it. That is, if we have the following HTML:

<article class="an-article"> 
<header class="an-article__header">
<img src="..." alt="...">
</header>
</article>

--

--

Gerardo Fernández
Gerardo Fernández

Written by Gerardo Fernández

Entre paseo y paseo con Simba desarrollo en Symfony y React

No responses yet