Skip to content

Instantly share code, notes, and snippets.

@simmo
Created August 7, 2015 14:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save simmo/ca5cf41063b436ee780f to your computer and use it in GitHub Desktop.
Save simmo/ca5cf41063b436ee780f to your computer and use it in GitHub Desktop.
JavaScript function to remove widows form elements.
// '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