Skip to content

Instantly share code, notes, and snippets.

@nickav
Last active May 3, 2019 04:13
Show Gist options
  • Save nickav/3879bf9d4498d86851ccea014d7a335c to your computer and use it in GitHub Desktop.
Save nickav/3879bf9d4498d86851ccea014d7a335c to your computer and use it in GitHub Desktop.
Don't let your headers dangle!
/**
* 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(' ') + '&nbsp;' + parts.slice(parts.length - minWords).join('&nbsp;')
}
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