Skip to content

Instantly share code, notes, and snippets.

@lsauer
Last active December 27, 2015 15:19
Show Gist options
  • Save lsauer/7346459 to your computer and use it in GitHub Desktop.
Save lsauer/7346459 to your computer and use it in GitHub Desktop.
JavaScript: Read TextContent from a tag and re-inject it as a HTML Script Element (blogger-plugins)
//www.lsauer.com, lo sauer 2013
//descr: looks for <code tags> and reinjects their content as a <script> Element;
// allows XHTML compliance with CDATA Containers
//from is-lib: DOMInsertScript
/* add this somewhere in your Blogger template*/
var bloggerplugins = bloggerplugins || {};
bloggerplugins.codetoscript = (function($, allowTextnode){
return function(){
var DOMInsertScript = function (str, toel) {
var el = document.createElement('script');
var attronload = toel.getAttribute('onload');
el.setAttribute('data-injected', 'true');
el.setAttribute('type', 'text/javascript');
if (!toel) {
toel = 'body'
};
el.textContent = str;
if(attronload){
el.setAttribute('onload', attronload);
}
(typeof toel == "string" ? document.querySelector(toel).parentNode : toel.parentNode).appendChild(el);
return el;
};
var _$ = $, istxt = allowTextnode;
_$('code[data-store]').each(
function (idx, el) {
//alternatively: el.childNodes.length
var leafs = Array.apply(this, el.childNodes);
//whitespaces between the container lead to additional Textnodes
for (var ei = 0,val = null; ei < leafs.length; ei++) {
val = leafs[ei];
if (val.nodeType == HTMLElement.COMMENT_NODE
|| val.nodeType == HTMLElement.CDATA_SECTION_NODE
|| (istxt && val.nodeType == HTMLElement.TEXT_NODE)) {
DOMInsertScript(val.data, el);
}
}
}
);
}
})(jQuery, true);
setTimeout(bloggerplugins.codetoscript, 2500);
/*lsauer.com 2013 - add this to the Template's CSS.
See this how-to: http://www.lsauer.com/2013/11/add-your-personal-stackoverflow-flair.html*/
code[data-store] {
display:none;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment