Question about each() in Jquery

Asked

Viewed 3,901 times

3

Because the code below only returns me the first "104 104" and not "104 106"

$(function(){
  $('#sortable li').each(function(){
    console.log($('#sortable li').attr('id'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<ul id="sortable">
  <li id="104"></li>
  <li id="106"></li>
</ul>

  • 1

    Can you join HTML? so we can respond more pedagogically. Briefly you are always using the same element... you should use console.log(this.id);. But if you join HTML it’s easier to understand the problem and answer.

4 answers

4

When you use $('#sortable li').attr('id') jQuery will return only the id of the first element that this selector finds.

When you use that line of code inside a .each() you’re not actually changing anything, and that’s why he gives the same answer both times.

However the selector $('#sortable li') returns all the elements you want and it makes sense to use the .each() to iterate them. Since jQuery assigns the iterated element to this within that function passed to .each() then to know the id just use this.id, as I mentioned in my comment earlier.

So just use it:

$('#sortable li').each(function(){
    console.log(this.id);
});

NOTE: Notice you’re missing }); at the end of your code, before the </script>.

2

Because at each turn of the loop you are making a new query to the DOM.
The $.each() structure allows you to access the element index and the element itself, without redoing the DOM query:

$('#sortable li').each(function(i, o){
   console.log(o.id);
});
  • the this returns the current for tb element inside the block. Ex: $(this).attr("id")

  • kkk I know Bruno, it is pq I wrote quickly here and I didn’t even notice. html ta on top Sergio. Marcelo, got it. But how do I get the ids of the two li. I’m getting beat up here for this shit. :)

  • accumulates them in an array or in a string, I do not know if I understood your doubt... each loop round it will expose you the id of the current and then vc accumulates in some variable that was declared out of the loop (each)

  • I just discovered......

0

-1

Hello here is an example where you will display the "id" attributes in a Javascript 'Alert':

 $("#sortable li").each(function(ui, e){
     alert($(this).attr("id"));
 });
  • It would be helpful if you added a small explanation to your reply.

Browser other questions tagged

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