Skip to content

Commit 2fa3bac

Browse files
committed
Core: Make jQuery objects iterable
Make iterating over jQuery objects possible using ES 2015 for-of: for ( node of $( "<div id=narwhal>" ) ) { console.log( node.id ); // "narwhal" } (partially cherry-picked from bb026fc) Fixes gh-1693
1 parent a022da7 commit 2fa3bac

File tree

3 files changed

+31
-0
lines changed

3 files changed

+31
-0
lines changed

src/core.js

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -477,6 +477,16 @@ jQuery.extend({
477477
support: support
478478
});
479479

480+
// JSHint would error on this code due to the Symbol not being defined in ES5.
481+
// Defining this global in .jshintrc would create a danger of using the global
482+
// unguarded in another place, it seems safer to just disable JSHint for these
483+
// three lines.
484+
/* jshint ignore: start */
485+
if ( typeof Symbol === "function" ) {
486+
jQuery.fn[ Symbol.iterator ] = deletedIds[ Symbol.iterator ];
487+
}
488+
/* jshint ignore: end */
489+
480490
// Populate the class2type map
481491
jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),
482492
function(i, name) {

test/.jshintrc

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@
2424
"DOMParser": false,
2525
"JSON": false,
2626
"Promise": false,
27+
"Symbol": false,
2728
"QUnit": false,
2829
"ok": false,
2930
"equal": false,

test/unit/core.js

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1519,3 +1519,23 @@ testIframeWithCallback( "Don't call window.onready (#14802)", "core/onready.html
15191519
equal( error, false, "no call to user-defined onready" );
15201520
}
15211521
);
1522+
1523+
test( "Iterability of jQuery objects (gh-1693)", function() {
1524+
/* jshint unused: false */
1525+
expect( 1 );
1526+
1527+
var i, elem, result;
1528+
1529+
if ( typeof Symbol === "function" ) {
1530+
1531+
elem = jQuery( "<div></div><span></span><a></a>" );
1532+
result = "";
1533+
1534+
try {
1535+
eval( "for ( i of elem ) { result += i.nodeName; }" );
1536+
} catch ( e ) {}
1537+
equal( result, "DIVSPANA", "for-of works on jQuery objects" );
1538+
} else {
1539+
ok( true, "The browser doesn't support Symbols" );
1540+
}
1541+
} );

0 commit comments

Comments
 (0)