Doubt about each () in Jquery

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><ulid="sortable">
  <li id="104"></li>
  <li id="106"></li>
</ul>
    
asked by anonymous 24.10.2015 / 20:07

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 this line of code inside a .each() you are not really changing anything, and hence it gives the same answer both times.

However, the $('#sortable li') selector returns all the elements you want, and it makes sense to use .each() to iterate. Since jQuery assigns the iterated element to this within that function passed to .each() so to know id just use this.id , #.

So just use:

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

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

    
24.10.2015 / 21:18
2

Because with every loop of the loop you are making a new query to the DOM. The $ .each (); allows you to access the element's index and the element itself, without redoing the DOM query:

$('#sortable li').each(function(i, o){
   console.log(o.id);
});
    
24.10.2015 / 20:30
0

Is that it?

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

link

    
24.10.2015 / 20:51
-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"));
 });
    
26.10.2015 / 13:47