Jaylen Jaylen - 5 months ago 8
jQuery Question

How to go over every item in an order list using jQuery?

When the page in load/reloaded, I need to loop over each each list item in the order list and apply some logic to it.

Here is what I have done but nothing is being printed in the console as expected.

$(function() {

$(window).load(function(){
//$( "#selected_sortable_control_570_0 li").each(function(index)
//$( "#selected_sortable_control_570_0 > li").each(function(index)
$( "ul.selected_sortable_control_570_0 > li").each(function(index)
{
console.log( $( this ).attr('id') );

});

});

});


Here is my HTML markup

<ul id="selected_sortable_control_570_0">
<li id="test1">Test 1</li>
<li id="test2">Test 2</li>
<li id="test3">Test 3</li>
</ul>


How can I correctly loop over each item?

A.J A.J
Answer

UL has id -> id="selected_sortable_control_570_0"

Use ul#selected_sortable_control_570_0 > li as selector in $ function.

Working snippet

$(function() {
  //$( "#selected_sortable_control_570_0 li").each(function(index)
  //$( "#selected_sortable_control_570_0 > li").each(function(index)
  $("ul#selected_sortable_control_570_0 > li").each(function(index) {
    console.log($(this).attr('id'));
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul id="selected_sortable_control_570_0">
  <li id="test1">Test 1</li>
  <li id="test2">Test 2</li>
  <li id="test3">Test 3</li>
</ul>

Note: Window load is not needed. Run the snippet it works.