3

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 ?

Jsbin

3
  • What exactly is your question ? Is it about the source code implementation and how it builds this order ? Commented Feb 25, 2013 at 8:17
  • Im asking why the first element in the array is A where it suppose to be d. Commented Feb 25, 2013 at 8:17
  • I did search it in source code but could not find the location where it actually adds the items in reverse order. Commented Feb 25, 2013 at 8:21

2 Answers 2

3

.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" ].

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

2 Comments

Simple answer to my simple question. Thanks.
creating a jQuery object that points to all three items in document order: you right.
1

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.