diff --git a/snippets/elementBiggerThanViewport.md b/snippets/elementBiggerThanViewport.md deleted file mode 100644 index 511573da7..000000000 --- a/snippets/elementBiggerThanViewport.md +++ /dev/null @@ -1,27 +0,0 @@ ---- -title: elementBiggerThanViewport -tags: beginner ---- - -Get elements in html bigger than the viewport width, useful when you're looking for what is causing the horizontal scroll - -- Returns all elements that are bigger than the viewport - -```js -const getElementsBiggerThanViewport = () => - let docWidth = document.documentElement.offsetWidth; - - [].forEach.call( - document.querySelectorAll('*'), - (el) => { - if (el.offsetWidth > docWidth) console.log('el', el); - } - ); - -``` - -```js -getElementsBiggerThanViewport(); //
...
-``` - - diff --git a/snippets/getElementsBiggerThanViewport.md b/snippets/getElementsBiggerThanViewport.md new file mode 100644 index 000000000..eab20310f --- /dev/null +++ b/snippets/getElementsBiggerThanViewport.md @@ -0,0 +1,25 @@ +--- +title: elementBiggerThanViewport +tags: browser,intermediate +--- + +Returns an array of HTML elements whose width is larger than that of the viewport's. + +- Use `HTMLElement.prototype.offsetWidth()` to get the width of the `document`. +- Use `Array.prototype.reduce()` on the result of `document.querySelectorAll()` to check the width of all elements in the document. + +```js +const getElementsBiggerThanViewport = () => { + const docWidth = document.documentElement.offsetWidth; + return [...document.querySelectorAll('*')].reduce((acc, el) => { + if (el.offsetWidth > docWidth) acc.push(el); + return acc; + }, []); +} +``` + +```js +getElementsBiggerThanViewport(); //
+``` + +