Skip to content

Instantly share code, notes, and snippets.

@liamnewmarch
Last active July 1, 2021 16:23
Show Gist options
  • Save liamnewmarch/54e8638da18f837c6f7271e748680ced to your computer and use it in GitHub Desktop.
Save liamnewmarch/54e8638da18f837c6f7271e748680ced to your computer and use it in GitHub Desktop.
Utility function parse a string as HTML, SVG or XML.
/**
* Utility function parse a string as HTML, SVG or XML.
*
* Example usage:
* parse('<a href="https://www.google.com">')[0].click();
*
* @param {string} string The string to parse [1]
* @param {type='text/html'} string The mime type to parse the string as [2]
* @returns {HTMLCollection} A HTML collection of the parsed elements
*
* [1]: https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument01
* [2]: https://developer.mozilla.org/en-US/docs/Web/API/DOMParser/parseFromString#Argument02
*/
export function parse(string, type = 'text/html') {
return new DOMParser().parseFromString(string, type).body.children;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment