Reputation: 148554
I have this html structure :
<body>
<a>
<b>
<c>
<d>
</d>
</c>
</b>
</a>
</body>
I use the <d>
element as the first node to start with.
Question :
var s= $("d").parentsUntil("body").andSelf().map(function(){
return this.tagName;
}).get();
It should start from the bottom and to top meaning the s
array should look like d,c,b,a
.
But it apparently look like : ["A", "B", "C", "D"]
Why is that ?
Upvotes: 3
Views: 410
Reputation: 382170
If you look at addBack's
code (to which andSelf
is an alias), you see this :
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( jQuery.unique(all) );
},
addBack: function( selector ) {
return this.add( selector == null ?
this.prevObject : this.prevObject.filter(selector)
);
}
So you see it calls unique
.
By looking further, you see
jQuery.unique = Sizzle.uniqueSort;
and
Sizzle.uniqueSort = function( results ) {
var elem,
duplicates = [],
i = 1,
j = 0;
// Unless we *know* we can detect duplicates, assume their presence
hasDuplicate = !support.detectDuplicates;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( ; (elem = results[i]); i++ ) {
if ( elem === results[ i - 1 ] ) {
j = duplicates.push( i );
}
}
while ( j-- ) {
results.splice( duplicates[ j ], 1 );
}
}
return results;
};
So, addBack
sorts the set as it ensures the added element isn't yet inside.
Upvotes: 1
Reputation: 8524
.andSelf()
causes jQuery to re-order the array.
You can try :
var s= $("d").parentsUntil("body").map(function(){
return this.tagName;
}).get();
The output of this code looks like:["C", "B","A" ]
.
Upvotes: 3