3

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?

3 Answers 3

9

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

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

Demo

1 Comment

This does not work because I am operating on JQuery object, which is not a true JavaScript array. No pop() method.
0

As people said, .remove() removes the element from the DOM. Another option than using slice on the final result is to use jquery's filtering before cloning the element:

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

1 Comment

Not a good idea in this case, because jQuery will need to actually test if each element matches the :last filter. This is not necessary because here we know from beforehand which elements match and which do not. Just something to keep in mind.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.