Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove the last element from JQuery array?

I want to select some DOM elements into a clone object then I want to remove the last item. After trying it in Chrome console I see that clone's length does not decrease.

Example from Chrome console:

crumbs =  $("span",$("div[style='width:390px;background-color:white;'")[0]).clone();

jQuery.fn.jQuery.init[114]

crumbs.last().remove()

[​…​​]

crumbs.length

114

As you see, length is still 114 elements. What am I missing?

like image 214
gradusas Avatar asked Feb 19 '26 10:02

gradusas


2 Answers

crumbs.last().remove() removes the last matched element from the DOM, it doesn't remove it from the jQuery object.

To remove an element from the jQuery object¹ use slice:

var withoutLastOne = crumbs.slice(0, -1);

¹ Actually this will create a new object that matches one less element instead of modifying your existing object. You will usually not care about the distinction, but should be aware of it.

like image 133
Jon Avatar answered Feb 20 '26 23:02

Jon


To remove last element from the array you can use below code too.

var arr = ["item1", "item2", "item3", "item4"];
arr.pop();

Demo

like image 22
Rakesh Kumar Avatar answered Feb 20 '26 23:02

Rakesh Kumar



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!