I have this code:
$("#test").siblings('p').remove();
$("#test").remove();
How can I chain this code instead of writing it separately?
I have this code:
$("#test").siblings('p').remove();
$("#test").remove();
How can I chain this code instead of writing it separately?
May be off topic.. you can change the view of the problem:
Guys sorry :( my decision isn't correct!!
Selector '~' isn't equal 'sibling'-method. '~' selects all sibling 'p'-elements that follow AFTER the '#test' element.
So i suggest another decision:
It is not enough elegant but the most faster way. Please check it 'http://jsperf.com/how-to-chain-this-code-stackoverflow-16009101'
Performance test result:
PS http://jsfiddle.net/Dpe59/
Try this :
I have to agree with the comment on the question; for readability and maintainability, use
andSelf
:Unfortunately, it's been deprecated. But if you're stuck on an older version of jquery like we are, it may be worthwhile.
edit: Though this works, don't do this. as Matt's comment says,
prevObject
is undocumentedYou want to use addBack() in this case:
EDIT
Firstly, for future visitors, if you're using jQuery version 1.8-, you're probably need to use andSelf() which is the predecessor of
addBack()
for compatibility issues.Secondly, both
end
andaddBack
will do the same task in this case but they're actually different perspective. Take a look at this HTML:If we're using
end()
:The result will look like this:
So when we use
end()
forson
, we're telling jQuery that it need to go back fromson
to parent set which isdad
and add classadult
.But when we use
addBack
:which will result in this:
So when we call
addBack
onson
, we're telling jQuery to pushdad
andson
into the same room and add new classadult
andoldster
to both of them.