About each, this and attr in jQuery

Asked

Viewed 53 times

2

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

  • 2

    I think this http://api.jquery.com/jquery.each/ and this http://api.jquery.com/attr/ are the best answers.

  • About this can read in this reply. And welcome! Next time the ideal is to ask a question per topic if there is not yet a question/answer about what you are looking for.

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...
});

The attr is responsible for taking the attributes of an element:

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

You can take any attribute of an element using only the attr

The this is a little more complicated, but I suppose the doubt relates to the selection of elements with the jquery, the this refers to the very 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.
});
  • Thank you very much!!! literally was what I needed to assimilate here!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.