diff --git a/README.md b/README.md index a6ef47f..cc172f4 100644 --- a/README.md +++ b/README.md @@ -94,6 +94,8 @@ if your [exception handler](http://glebbahmutov.com/blog/catch-all-errors-in-ang * [github-pull-request-template.js](github-pull-request-template.js) - better GitHub pull request text, based on the blog post [Enforce standards while submitting a pull request](http://krasimirtsonev.com/blog/article/enforce-standards-while-submitting-a-pull-request) by [Krasimir Tsonev](https://github.com/krasimir). +* [remove-all-but.js](remove-all-but.js) - removes all elements in the page, except the ones in +the trees with specified selectors. Can be used to quickly clean up the page and leave just the essentials. All snippets, including mine are distributed under MIT license. @@ -102,6 +104,9 @@ All snippets, including mine are distributed under MIT license. You can update local code snippets by downloading new versions from this github repository. Create a new code snippet and copy the source from [update-code-snippets.js](update-code-snippets.js). +Note: the approach below does not work any more, +see [the open issue](https://github.com/bahmutov/code-snippets/issues/23). + You will run this code snippet in an unusual way. First, open any web page, even an empty tab. Open the DevTools in **undocked** mode (Command+Option+I on Mac). Then open the DevTools **again**, *while focused* on the first DevTools. This will open the second DevTools instance with the source for the diff --git a/remove-all-but.js b/remove-all-but.js new file mode 100644 index 0000000..eb6194c --- /dev/null +++ b/remove-all-but.js @@ -0,0 +1,52 @@ +/* +Removes all elements except for the trees rooted +in the given selectors. + +For example, given a document + +body + div.foo + span + div#bar + div#baz + hello + +and command with selectors ('.foo', '#baz') will leave +everything in place, but command ('#baz') will leave just + +body + div#bar + div#baz + hello +*/ +(function hideAllBut() { + function toArray(what) { + return Array.prototype.slice.call(what, 0); + } + const selectors = toArray(arguments); + if (!selectors.length) { + throw new Error('Need at least one selector to leave'); + } + + const keep = selectors.map(function (selector) { + return document.querySelector(selector); + }); + + function shouldKeep(el) { + return keep.some(function (keepElement) { + return keepElement.contains(el) || el.contains(keepElement); + }); + } + + const all = toArray(document.body.querySelectorAll('*'), 0); + var removed = 0; + + all.forEach(function (el) { + if (!shouldKeep(el)) { + el.parentNode.removeChild(el); + removed += 1; + } + }); + + console.log('removed %d elements', removed); +}('.foo', '#baz')); diff --git a/utils/.jshintrc b/utils/.jshintrc index 7dd9840..0f1b5db 100644 --- a/utils/.jshintrc +++ b/utils/.jshintrc @@ -30,7 +30,7 @@ "debug" : false, "eqnull" : false, "es5" : false, - "esnext" : false, + "esnext" : true, "moz" : false, "evil" : false, "expr" : false,