UNPKG

bona

Version:

Super lightweight microframework focused on static websites and landing pages.

62 lines (58 loc) 2.27 kB
/** * Replace nodes from a given document by selector. * * @param {string} selector Selector. * @param {Document} doc Source document. * @param {boolean} [removeNodes] Remove non-existent nodes. * @param {boolean} [extendNodes] Extend or replace new nodes. */ export const replaceNodesBySelector = (selector, doc, removeNodes = true, extendNodes = false) => { const nodes = document.querySelectorAll(selector); const newNodes = doc.querySelectorAll(selector); nodes.forEach((el, index) => { if (newNodes[index]) { if (extendNodes) { el.append(...newNodes[index].childNodes); } else { // DOMParser.parseFromString fails <source> in <picture> and <video> in Safari/FF, so wrap it in div // https://stackoverflow.com/questions/58240755/ // el.replaceWith(newNodes[index]); const temp = document.createElement('div'); temp.innerHTML = newNodes[index].outerHTML; el.replaceWith(temp.firstElementChild); } } else if (removeNodes) { el.remove(); } }); }; /** * Replace nodes from a given document by selectors. * * @param {string[]} selectors Selectors. * @param {Document} doc Source document. * @param {boolean} [removeNodes] Remove non-existent nodes. * @param {boolean} [extendNodes] Extend or replace new nodes. */ export const replaceNodesBySelectors = (selectors, doc, removeNodes = true, extendNodes = false) => { selectors.forEach((selector) => { replaceNodesBySelector(selector, doc, removeNodes, extendNodes); }); }; /** * Check an anchor for eligibility. * * @param {HTMLAnchorElement} el Anchor element. * @param {RegExp} [checkUrlRegExp] Check the URL using RegExp. * @param {string} [host] Current host. * @return {boolean} */ export const checkAnchorEligibility = (el, checkUrlRegExp, host = window.location.host) => { if (el.tagName !== 'A' || !el.href || el.host !== host) return false; if (el.getAttribute('target') || el.hasAttribute('download')) return false; if (checkUrlRegExp) { const match = el.href.match(checkUrlRegExp); if (!match || match[1]) return false; } return true; };