Created
March 23, 2017 11:09
-
-
Save evolutionxbox/84b0d2ada3f7f385d15af73ba9591b94 to your computer and use it in GitHub Desktop.
Wrap those rogue text nodes (inside table-cells)!
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
// Wrap all "rogue" textNodes in a paragraph | |
(function wrapAllRogueTextNodes () { | |
var allowedElements = [ 'A', 'B', 'BIG', 'I', 'SMALL', 'TT', 'ABBR', 'ACRONYM', 'CITE', 'DFN', 'EM', 'KBD', 'STRONG', 'TIME', 'BR', 'SUB', 'SUP' ]; | |
function arrayFrom (arrayLike) { | |
return Array.prototype.slice.call(arrayLike); | |
} | |
function wrapInParagraph (nodes) { | |
if (nodes.length > 0) { | |
var p = document.createElement('p'); | |
nodes[0].parentNode.insertBefore(p, nodes[0]); | |
nodes.forEach(function (node) { | |
p.appendChild(node); | |
}); | |
return p; | |
} | |
} | |
function wrapAllInParagraph (arrays) { | |
return arrays.map(wrapInParagraph); | |
} | |
function splitAtForbiddenElements (nodes) { | |
var result = []; | |
nodes.forEach(function (node, index) { | |
if (!(node.nodeType === 3 || allowedElements.indexOf(node.nodeName) > -1) || index === 0) { | |
result.push([]); | |
} | |
if (node.nodeType === 3 || allowedElements.indexOf(node.nodeName) > -1) { | |
result[result.length - 1].push(node); | |
} | |
}); | |
return result; | |
} | |
function childNodesAsArray (node) { | |
return arrayFrom(node.childNodes); | |
} | |
function hasTextNodes (node) { | |
return (node.nodeType === 3 && node.textContent.trim() !== ''); | |
} | |
function filterNoText (nodes) { | |
return nodes.some(hasTextNodes); | |
} | |
function filterComments (node) { | |
return node.nodeType !== 8; | |
} | |
function filterBlankText (node) { | |
return !(node.nodeType === 3 && node.textContent.trim() === '') | |
} | |
function noCommentsOrBlankText (nodes) { | |
return nodes | |
.filter(filterComments) | |
.filter(filterBlankText); | |
} | |
var nodes = arrayFrom(document.querySelectorAll('td')); | |
nodes | |
.map(childNodesAsArray) | |
.filter(filterNoText) | |
.map(noCommentsOrBlankText) | |
.map(splitAtForbiddenElements) | |
.map(wrapAllInParagraph); | |
}()); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment