Last active
February 4, 2022 22:30
-
-
Save bitsmanent/2061619b984180bc8470133d8ab9cd7d to your computer and use it in GitHub Desktop.
Universal HTML rendering routine (work in progress) [Superseded by domapply]
This file contains hidden or 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
/* Superseded by domapply: | |
* https://gist.github.com/clamiax/e053d486c28e5101ddf6a1739a5151c7 */ | |
/* This may eventually be included in utils.js[0] at some point, if everything | |
* will works as expected. | |
* [0] https://gist.github.com/clamiax/e1db98deaf94bb1ccf8556d993245afb */ | |
function applytodom(dst, src) { | |
var par, len, atts, i, has; | |
if(!(dst && src)) | |
return; | |
if(dst.tagName != src.tagName) { | |
par = dst.parentElement; | |
par.insertBefore(src.cloneNode(true), dst); | |
par.removeChild(dst); | |
return; | |
} | |
if(src.nodeType != Node.ELEMENT_NODE) { | |
if(src.nodeType == Node.TEXT_NODE) { | |
if(dst.nodeValue != src.nodeValue) | |
dst.nodeValue = src.nodeValue; | |
} | |
else | |
console.debug(`${src.nodeType}: unknown node type; ignored.`); | |
return; | |
} | |
/* sync attributes */ | |
has = {}; | |
atts = (src.attributes||[]); | |
for(i = 0, len = atts.length; i < len; ++i) { | |
has[atts[i].name] = 1; | |
/* properties */ | |
if(dst[atts[i].name] != undefined && dst[atts[i].name] != atts[i].value) | |
dst[atts[i].name] = atts[i].value; | |
/* attributes */ | |
if(dst.getAttribute(atts[i].name) != atts[i].value) | |
dst.setAttribute(atts[i].name, atts[i].value); | |
} | |
/* remove unmatching attributes */ | |
atts = (dst.attributes||[]); | |
for(i = 0, len = atts.length; i < len && atts[i]; ++i) { | |
if(!has[atts[i].name]) { | |
dst.removeAttribute(atts[i].name); | |
--i; | |
} | |
} | |
/* reset checked property if needed */ | |
if(dst.checked && !dst.getAttribute("checked")) | |
dst.checked = false; | |
/* apply children */ | |
for(i = 0, len = src.childNodes.length; i < len; ++i) { | |
if(!dst.childNodes[i]) { | |
dst.appendChild(src.childNodes[i].cloneNode(true)); | |
continue; | |
} | |
applytodom(dst.childNodes[i], src.childNodes[i]); | |
} | |
/* remove exceeding nodes */ | |
while(dst.childNodes[i]) | |
dst.childNodes[i].parentNode.removeChild(dst.childNodes[i]); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment