This is not a suggestion for the jQuery core; it’s just something I required recently that some of you may find useful/intriguing…
jQuery.fn.map = (function(_map) { return function(toMap, prop, jQueryOb) { if (typeof toMap === 'string') { var parts = toMap.match(/(\:|[^:])+/g), method = parts.shift(), args = parts, mapped = _map.call(this, function(){ var $this = $(this), result = $this[method].apply( $this, args ); return prop ? result[prop] : result; }); return jQueryOb ? mapped : mapped.get(); } else { return _map.apply(this, arguments); } }; })(jQuery.fn.map); // Note: this only modifies $.fn.map; not $.map |
It allows you to pass a string to $(collection).map(...)
instead of a function; it’s useful for returning attributes, DOM properties, CSS styles or data tied to each element without having to spend time/space writing a function, e.g.
$('a').map('attr:href'); // => ['http://abc.com', 'http://123.com', ... (all HREFs) $('p').map('css:fontSize'); // => ['16px', '12px', '19px' ... (all font-sizes) $('.class').map('offset', 'left'); // => ['200px', '430px', ... (all left offsets) $('div').map('data:someData'); // => ['data', ... (added via jQuery.fn.data) |
The first argument is split at each colon (use to escape a colon), the first part of the split string is assumed to be the jQuery method name which you want to call (e.g.
"css" => $().css()
). All remaining parts are assumed to be arguments for that method. The second argument (to map()
) is an optional property to access following retrieval; this is demonstrated with the “offset” example in the code above. The last argument is a boolean; passing true will make it return a jQuery object instead of a real array.
Thanks for reading! Please share your thoughts with me on Twitter. Have a great day!
Earth to James 🙂
Seriously, this is ‘out-there’ in terms of originality and coolness.
Don’t let school change you too much, ok?