About each, this and attr in jQuery [closed]

2
Good morning friends, I have a big question regarding these attributes (if I may say so), I would actually like to really understand how each of them works, I wanted to understand why use each one of them, since I already thank and apologize if the question was somehow bad.

    
asked by anonymous 26.01.2017 / 14:08

1 answer

3

The each is basically to make a loop through an array or object, for example:

var meu_array = [1,2,3,4,5];
$.each(meu_array, function(index, value){
    console.log(index); // Exibira o numero do indice. 0, 1, 2...
    console.log(value); // Exibira o conteudo do elemento atual. 1,2,3...
});

attr is responsible for taking the attributes of an element:

<div class="minha_classe" id="meu_id"></div>
$('.minha_classe').attr('id');

You can get any attribute of an element using only attr

The this is a little more complicated, but I suppose that the doubt refers to the selection of elements with jquery , this refers to the object that was selected:

<div class="minha_classe" id="meu_id"></div>
$('.minha_classe').on('click', function() {
    console.log(this);
    // Exibira o elemento selecionado "<div class="minha_classe" id="meu_id"></div>"

    console.log($(this));
    // Exibira o elemento citado acima com funções "embutidas" do jquery como por exemplo o attr.
});
    
26.01.2017 / 14:15