admin管理员组

文章数量:1242837

I have an unordered list that I am prepending data to as follows:

jQuery("#mylist").prepend(newItem);  

When the list reaches a certain size I need to remove the first item that was inserted before adding the new one.

How would I get the first item to remove based on accessing the ordered list by it's id.

Something like:

 jQuery("#mylist")[0].remove();

Thanks

I have an unordered list that I am prepending data to as follows:

jQuery("#mylist").prepend(newItem);  

When the list reaches a certain size I need to remove the first item that was inserted before adding the new one.

How would I get the first item to remove based on accessing the ordered list by it's id.

Something like:

 jQuery("#mylist")[0].remove();

Thanks

Share Improve this question edited Nov 13, 2012 at 17:03 Robert Koritnik 105k56 gold badges284 silver badges413 bronze badges asked Nov 13, 2012 at 17:02 JIbber4568JIbber4568 8394 gold badges16 silver badges34 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 13

Since you mentioned ordered list, im assuming #mylist contains li tags inside, thus this should work

jQuery("#mylist li:first-child").remove();

I see you are prepending there, In case you want to remove the last element then

jQuery("#mylist li:last-child").remove();

Because you're doing .prepend(), the first item inserted would be the last item in the list, so you'd do this:

$("#mylist").children().last().remove();

The [0] is the same as get(0) which is selecting the DOM element. The DOM does not have .remove(). Plus you are selecting the parent element and not the children.

You can use eq(0) to select the first

 jQuery("#mylist li").eq(0).remove();

there are other jQuery selectors/methods such as .first(), :first, :first-child

本文标签: javascriptJQuery remove first item from ordered listStack Overflow