Skip to content

Instantly share code, notes, and snippets.

@scsskid
Last active September 1, 2021 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save scsskid/0bc649f5e2e9afe2135b48585bbc29fb to your computer and use it in GitHub Desktop.
Save scsskid/0bc649f5e2e9afe2135b48585bbc29fb to your computer and use it in GitHub Desktop.
[getDataFromHtml] #dom #helpers
//Src: https://github.com/swup/swup/blob/master/src/helpers/getDataFromHtml.js
import { queryAll } from '../utils';
const getDataFromHtml = (html, containers) => {
let fakeDom = document.createElement('html');
fakeDom.innerHTML = html;
let blocks = [];
for (let i = 0; i < containers.length; i++) {
if (fakeDom.querySelector(containers[i]) == null) {
// page in invalid
return null;
} else {
queryAll(containers[i]).forEach((item, index) => {
queryAll(containers[i], fakeDom)[index].setAttribute('data-swup', blocks.length); // marks element with data-swup
blocks.push(queryAll(containers[i], fakeDom)[index].outerHTML);
});
}
}
const json = {
title: fakeDom.querySelector('title').innerText,
pageClass: fakeDom.querySelector('body').className,
originalContent: html,
blocks: blocks
};
// to prevent memory leaks
fakeDom.innerHTML = '';
fakeDom = null;
return json;
};
export default getDataFromHtml;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment