I have this code:
$(\"#test\").siblings(\'p\').remove();
$(\"#test\").remove();
How can I chain this code instead of writing it separately?
The end()
method is useful primarily when exploiting jQuery's chaining properties. When not using chaining, we can usually just call up a previous object
by variable name, so we don't need to manipulate the stack.
The new set of elements is pushed onto a stack that is maintained inside the object
. Each successive filtering method pushes a new element set onto the stack. If we need an older element set, we can use end()
to pop the sets back off of the stack.
I guess with use of .end()
like this:
$("#test").siblings('p').remove().end().remove();
You can find a fiddle
Now what is happening with this code snippet above:
Suppose this HTML markup:
This is supposed to be removed.
And this to be removed too.
when script executes:
$("#test").siblings('p').remove()
this block removes the sibling item from the view, then markup will be updated like:
This is supposed to be removed.
and if we chain it with .end()
$("#test").siblings('p').remove().end()
it gets back to the stack at #test
div then the next part of the script gets fired
$("#test").siblings('p').remove().end().remove();
//--^^^^^^^^^^^^^^^----this next part
and #test
gets removed from the view and your final markup output will be like: