There is a web page I visit which I would like to print. However, I only want to print a couple of things on it, not everything.
So, I am making a bookmarklet that I can use whenever I visit the page to hide everything from the printer except what I want to print.
The site already has a class, 'd-print-none', to hide an element from the printer.
The following code is the javascript I made to base my bookmarklet on.
My idea is to first apply the 'd-print-none' class to everything. Then selectively remove it.
I remove the class from the element that contains what I would like to print as well as any of its children.
Then I recursively remove it from the parents until I reach the document element.
function removeClass(t_selector, t_class){
document.querySelectorAll(t_selector + ' *').forEach(x=>x.classList.remove(t_class))
node = document.querySelector(t_selector)
while (node && node.nodeType != Node.DOCUMENT_NODE) {
node.classList.remove.(t_class);
node = node.parentNode;
}
}
document.querySelectorAll( '*' ).forEach(x=>x.classList.add('d-print-none'))
removeClass('app-flex-chart', 'd-print-none')
removeClass('app-flex-grid', 'd-print-none')
Adding the class to all elements was pretty straightforward and succinct as was removing it from all of the target element's children.
Climbing the tree to apply it to the element itself and any of its parents was more verbose and error prone. Sadly, there appears to be no css selector to find all parents of an element.
I paired the loop down to be as succinct and readable as I could.
I am looking for ideas on how to make it more robust, succinct, or readable. Open to any and all suggestions and criticisms.
For that while loop, I had to check if the node I was on existed and check to make sure it wasn't the document node, either case would cause an error.
EDIT: To show generic structure of page
<html>
<head>...</head>
<body>
<many>
<nested>
<tags>
<app-flex-chart>
<many-more-nested-tags>Actual Content</many-more-nested-tags>
</app-flex-chart>
</tags>
</nested>
</many>
</body>
</html>
The app-flex-chart tag is the only unique piece along the chain to the content. All other classes and tags seem to be reused throughout the page.