30秒学会 JavaScript 片段 · 2023年8月9日

30秒学会 JavaScript 片段 – Get elements bigger than viewport

Returns an array of HTML elements whose width is larger than that of the viewport’s.

  • Use HTMLElement.offsetWidth to get the width of the Document.
  • Use Array.prototype.filter() on the result of Document.querySelectorAll() to check the width of all elements in the document.

代码实现

const getElementsBiggerThanViewport = () => {
  const docWidth = document.documentElement.offsetWidth;
  return [...document.querySelectorAll('*')].filter(
    el => el.offsetWidth > docWidth
  );
};

getElementsBiggerThanViewport(); // <div id="ultra-wide-item" />

翻译自:https://www.30secondsofcode.org/js/s/get-elements-bigger-than-viewport