Question : How do I insert li into ul based on an attribute?

Hi,
I have a <ul> like below and i need to insert a <li> based on msg-time attribute.
If msg-time=250, i need to insert it between msg-time 200 and 300

Need to insert
 <li  msg-time="250" class="msg-item"></li>

into
<ul id="msg-list">  
        <li  msg-time="100" class="msg-item"></li>
        <li  msg-time="200" class="msg-item"></li>
        <li  msg-time="300" class="msg-item"></li>  
        <li  msg-time="400" class="msg-item"></li>  
        <li  msg-time="500" class="msg-item"></li>  
</ul>

What is the best way? I may have many <li>, so I need to be efficient.

Thanks
Jamie

Answer : How do I insert li into ul based on an attribute?

Hey

If you mean that the 250 could be a variable and could change, and depending on what the value is, put it between the closest two numbers, you could do something like this.

put the msg_time into a variable
set the element to be added to the list
loop through the list
get the msg_time of the current list item
get the msg_time of the next list item
then test to see if msgtime is between these 2 numbers, if it is, add the new element

            msg_time = 250;
            new_list_element = ' <li msg-time="' + msg_time + '" class="msg-item">new</li> ';
            
            $('#msg-list li').each(function() {
                  
                  minimum = $(this).attr('msg-time');
                  maximum = $(this).next().attr('msg-time');
            
            
                  if(msg_time >= minimum && msg_time <= maximum) {
                      $(this).after(new_list_element);
                  }

                                                            
              });
Random Solutions  
 
programming4us programming4us