Skip to content

Instantly share code, notes, and snippets.

@kthwaite
Last active August 3, 2020 13:18
Show Gist options
  • Save kthwaite/5934d0b2253cce2b65dfbd39e3186dab to your computer and use it in GitHub Desktop.
Save kthwaite/5934d0b2253cce2b65dfbd39e3186dab to your computer and use it in GitHub Desktop.
/**
* Extract and data from the DOM in JSON format.
* @param selector {string} - Selector to query.
* @param extractor {function} - Operation to apply to each DOM element.
* @param filename {string}
*/
function selectorToJson(selector, extractor, filename) {
const elements = document.querySelectorAll(selector);
const data = Array.from(elements).map(extractor);
if(filename == null) {
return data;
}
const blob = new Blob([JSON.stringify(data)], {type: 'text/json'});
const a = document.createElement('a');
a.download = filename;
a.href = window.URL.createObjectURL(blob);
a.dataset.downloadurl = ['text/json', a.download, a.href].join(':');
const evt = new MouseEvent('click');
a.dispatchEvent(evt);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment