Created
August 7, 2015 14:24
-
-
Save simmo/ca5cf41063b436ee780f to your computer and use it in GitHub Desktop.
JavaScript function to remove widows form elements.
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
// 'elements' should be a string of the CSS selectors you wish to match | |
function widowKiller(elements) { | |
var nodes = document.querySelectorAll(elements); | |
function removeWidow(element) { | |
var walk = document.createTreeWalker(element, NodeFilter.SHOW_TEXT, null, false); | |
var node, arr; | |
while(node = walk.nextNode()) { | |
arr = node.nodeValue.split(' '); | |
arr.push(arr.splice(-2, 2).join('\u00A0')); | |
node.nodeValue = arr.join(' '); | |
} | |
} | |
for (var i = nodes.length - 1; i >= 0; i--) { | |
removeWidow(nodes[i]); | |
} | |
} | |
// Example usage | |
widowKiller('p,h3,li:lastchild'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment