Show Size of Elements Using JavaScript

I was recently doing a lot of layouting pages to later be printed, so showing how big certain elements are was of help to me.

This is a JavaScript function that does just that.

It uses a background image API to get images in the right size with the width and height rendered into them as text. It supports different units, like cm or inches, to be displayed using displayConversionFactor and displayUnit.


function showSizeOfElements(
  displayConversionFactor = 1,
  displayUnit = "px"
) {
  elements.forEach((element) => {
    var width = element.offsetWidth;
    var height = element.offsetHeight;
    var a = Math.round(width * displayConversionFactor * 100) / 100;
    var b = Math.round(height * displayConversionFactor * 100) / 100;
    var description = `${a}*${b}${displayUnit}`;
    var url = `${width}&h=${height}&tc=blue&bg=white&t=${description}`; = `url('${url}')`;

// Show sizes in pixels

// Show sizes in cm
showSizeOfElements(document.querySelectorAll(".something"), 0.026458, "cm");

// Show sizes in inches
showSizeOfElements(document.querySelectorAll(".something"), 0.0104166667, "in");


See also