-
Notifications
You must be signed in to change notification settings - Fork 199
/
Copy pathremove-all-but.js
51 lines (41 loc) · 1.08 KB
/
remove-all-but.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/*
Removes all elements except for the trees rooted
in the given selectors. Selectors are queried using querySelectorAll
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() {
'use strict';
const selectors = Array.from(arguments);
if (!selectors.length) {
throw new Error('Need at least one selector to leave');
}
const keep = selectors.reduce(function (all, selector) {
return all.concat(Array.from(document.querySelectorAll(selector)));
}, []);
function shouldKeep(el) {
return keep.some(function (keepElement) {
return keepElement.contains(el) || el.contains(keepElement);
});
}
const all = Array.from(document.body.querySelectorAll('*'));
var removed = 0;
all.forEach(function (el) {
if (!shouldKeep(el)) {
el.parentNode.removeChild(el);
removed += 1;
}
});
console.log('removed %d elements', removed);
}('.foo'));