Pass a jquery selection function to Javascript

0

Investigating a bit of jquery, I found this function:

$(document).on('click', '.class', function () {
    let element = $(this)[0]
    let search = $(element).attr('dat')
    console.log(element)
})

I am learning javascript - I still do not know much, I realized that with this function I save the selected element, I would like to know how the function from above could pass to javascript, and also if possible explain to me what is doing the this and the [0] , I've seen the this very often, but I find it hard to understand.

    
asked by Diego Guatibonza 03.01.2019 в 21:26
source

1 answer

4

We are part by part

  • jQuery is a library for JavaScript
  • So that jQuery can do element manipulation it usually wraps the native objects.
  • To wrap objects using a function called $() that is equivalent to jQuery() . The symbol $ has nothing special, it is an identifier, it could have been called a , x , etc.
  • Then $(document) means that it takes the document element that is the visible part of the window and wraps it around. No equivalent required, document can be used directly.
  • .on('click', '.class', function() { ... }) is the way jQuery adds an event handler, in this case, click of any part of the document.
  • The equivalent would normally be .addEventListener('click', function(event) { ... }) . Where event is a parameter that the browser will provide us with information about the event. You can give it any name.
  • There is a detail in the second parameter. '.class' is a selector, when you pass that parameter signficia that should only trigger the event handler when the element fits with the filter. In this case you have a class called class
  • In this specific case, this within on() refers to the element that made match with the selector and that triggered the event. The value of this may vary depending on how the invocation was made.
  • $(this) is again to convert it into a jQuery object but since there may have been multiple elements that were selected, use [0] to choose the first one. This is the syntax for normal JavaScript fixes.

Then the equivalent in pure JavaScript would be:

document.addEventListener('click', function(event) {
    let element = event.target;

    if (element.classList.contains('class')) {
        let search = element.getAttribute('dat');
        console.log(element); 
    }
});
    
answered by 03.01.2019 / 22:52
source