Last active
September 1, 2021 14:53
-
-
Save scsskid/0bc649f5e2e9afe2135b48585bbc29fb to your computer and use it in GitHub Desktop.
[getDataFromHtml] #dom #helpers
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//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