Last active
January 31, 2017 21:04
-
-
Save fotinakis/f5438e861d75f509bf3f to your computer and use it in GitHub Desktop.
Pure JavaScript: Hide all text on the page but preserve element spacing.
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
function textNodesUnder(el){ | |
var n, a = []; | |
var walk = document.createTreeWalker(el, NodeFilter.SHOW_TEXT, null, false); | |
while (n = walk.nextNode()) { a.push(n); } | |
return a; | |
} | |
// Normalize all text nodes (merge adjacent nodes). | |
var elements = document.getElementsByTagName('*'); | |
for (var i = 0; i < elements.length; i++) { | |
elements[i].normalize(); | |
} | |
elements = textNodesUnder(document.getElementsByTagName('body')[0]); | |
for (var i = 0; i < elements.length; i++) { | |
// Skip empty nodes. | |
if (elements[i].nodeValue.trim() == '') { continue; } | |
// Create a wrapper span with opacity: 0 and replace the current textNode. | |
var wrapperSpan = document.createElement('span'); | |
wrapperSpan.setAttribute('style', 'opacity: 0'); | |
wrapperSpan.appendChild(elements[i].cloneNode()); | |
elements[i].parentNode.replaceChild(wrapperSpan, elements[i]); | |
} |
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
// Or, in jQuery: | |
$('*').contents().filter(function(i, node) { | |
return node.nodeType === 3 && node.textContent.trim() !== ''; | |
}).wrap('<span style="opacity: 0"></span>'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment