Skip to content

Instantly share code, notes, and snippets.

@grantcodes
Last active October 30, 2017 23:02
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grantcodes/5eb16ffc6246d4b4c05b01e93c369396 to your computer and use it in GitHub Desktop.
Save grantcodes/5eb16ffc6246d4b4c05b01e93c369396 to your computer and use it in GitHub Desktop.
Simple function to get all rel links from a html string
export default function (htmlString, url) {
let rels = {};
let baseUrl = url;
const doc = new DOMParser().parseFromString(htmlString, 'text/html');
const baseEl = doc.querySelector('base[href]');
const relEls = doc.querySelectorAll('[rel][href]');
if (baseEl) {
const value = baseEl.getAttribute('href');
const url = new URL(value, url);
baseUrl = url.toString();
}
if (relEls.length) {
relEls.forEach((relEl) => {
const names = relEl.getAttribute('rel').toLowerCase().split("\\s+");
const value = relEl.getAttribute('href');
if (names.length && value !== null) {
names.forEach((name) => {
if (!rels[name]) {
rels[name] = [];
}
const url = new URL(value, baseUrl).toString();
if (rels[name].indexOf(url) === -1) {
rels[name].push(url);
}
});
}
});
}
return rels;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment