Last active
May 3, 2019 04:13
-
-
Save nickav/3879bf9d4498d86851ccea014d7a335c to your computer and use it in GitHub Desktop.
Don't let your headers dangle!
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
/** | |
* Don't let your headers dangle! | |
* | |
* My super cool blog | |
* thing <<<< dangling! | |
*/ | |
function noDangle(selector, minWords) { | |
selector = selector || 'h1,h2,h3,h4,h5,h6' | |
minWords = minWords || 1 | |
var undangle = function(text, minWords) { | |
minWords = minWords || 1 | |
var parts = text.split(/\s/) | |
if (parts.length < 2) return text | |
return parts.slice(0, parts.length - minWords).join(' ') + ' ' + parts.slice(parts.length - minWords).join(' ') | |
} | |
Array().forEach.call(document.querySelectorAll(selector), function(el) { | |
while (el.children.length) { | |
el = el.children[el.children.length - 1] | |
} | |
var text = el.innerText | |
var replacement = undangle(text, minWords) | |
el.innerHTML = replacement | |
}) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment