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?
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.
To remove last element from the array you can use below code too.
var arr = ["item1", "item2", "item3", "item4"];
arr.pop();
Demo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With