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.

Code

function showSizeOfElements(
  elements,
  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 = `https://via.assets.so/img.jpg?w=${width}&h=${height}&tc=blue&bg=white&t=${description}`;
    element.style.backgroundImage = `url('${url}')`;
  });
}

// Show sizes in pixels
showSizeOfElements(document.querySelectorAll(".something"));

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

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

Demo

See also