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 badges3 Answers
Reset to default 13Since 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