You can write a jQuery plugin for this script. :)
The following code below will return an array of heights based on the provided selectors.
[20,30,80]
JQuery plugin
(function($) { $.fn.heights = function() { return this.map(function() { return $(this).height(); }).toArray(); }; }(jQuery)); var heights = $('.header-wrapper, #top-bar, #new-showroom-header').heights(); document.body.innerHTML = JSON.stringify(heights);
body { font-family: monospace; white-space: pre; } .header-wrapper { height: 20px; } #top-bar { height: 30px; } #new-showroom-header { height: 80px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="page-wrapper"> <div class="header-wrapper"></div> <div id="top-bar"></div> <div id="new-showroom-header"></div> </div>
Alternatively, you can create a height cache with your selectors.
{ "html>body>div>.header-wrapper": 20, "html>body>div>#top-bar": 30, "html>body>div>#new-showroom-header": 80 }
(function($) { $.reduce = function(arr, fn, initVal) { if (Array.prototype.reduce) { return Array.prototype.reduce.call(arr, fn, initVal); } $.each(arr, function(i, val) { initVal = fn.call(null, initVal, val, i, arr); }); return initVal; }; $.fn.heights = function() { return $.reduce(this, function(map, el) { map[$(el).fullSelector()] = $(el).height(); return map; }, {}); }; $.fn.fullSelector = function() { var sel = $(this) .parents() .map(function() { return this.tagName.toLowerCase(); }) .get() .reverse() .concat([this.nodeName]) .join(">"); var id = $(this).attr('id'); if (id) { sel += '#' + id; }; var cls = $(this).attr('class'); if (cls) { sel += '.' + $.trim(cls).replace(/\s/gi, '.'); }; return sel; } }(jQuery)); var heights = $('.header-wrapper, #top-bar, #new-showroom-header').heights(); document.body.innerHTML = JSON.stringify(heights, null, 2);
body { font-family: monospace; white-space: pre; } .header-wrapper { height: 20px; } #top-bar { height: 30px; } #new-showroom-header { height: 80px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <div class="page-wrapper"> <div class="header-wrapper"></div> <div id="top-bar"></div> <div id="new-showroom-header"></div> </div>
The credit for the selector algorithm goes to Jesse Gavin .
source share