Skip to content

Instantly share code, notes, and snippets.

@nielsenrc
Created September 9, 2015 19:37
Show Gist options
  • Save nielsenrc/6a27fc0f18f42c426add to your computer and use it in GitHub Desktop.
Save nielsenrc/6a27fc0f18f42c426add to your computer and use it in GitHub Desktop.
JS | Find Widest Element on Page with Javascript
var widest = null;
// remember the width of the "widest" element - probably faster than calling .width()
var widestWidth = 0;
$("div").each(function() {
if (widest == null)
{
widest = $(this);
widestWidth = $(this).width();
}
else
if ($(this).width() > widestWidth) {
widest = $(this);
widestWidth = $(this).width();
document.write($(this).attr("class"));
document.write($(this).attr("id"));
}
});
@OZZlE
Copy link

OZZlE commented Jul 11, 2018

Below is working solution, the one above only looks at div's + doesn't take into account that parent divs will in most cases be as wide as their children. Also the one above doesn't take into account if an element has a lot of padding making it very wide.

I haven't optimized it towards any speed because I am just using this myself to debug when there is vertical scroll on a page to try to figure out where it comes from. But it's only O(n*2) === O(n) (for those who knows Ordo)

var widest = null;
var widestWidth = 0;
jQuery("html *").each(function() {
  if (jQuery(this).outerWidth() > widestWidth) {    
    widest = jQuery(this);
    widestWidth = jQuery(this).outerWidth();
  }
});
jQuery("html *").each(function() {
  var $this = $(this);
  if (jQuery.contains(widest[0], $this[0]) && jQuery(this).outerWidth() >= widestWidth) {
    widest = $this;
    widestWidth = jQuery(this).outerWidth();
  }
});
console.log(widest[0]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment