Skip to content

Instantly share code, notes, and snippets.

@brendan-c
Last active September 5, 2022 21:41
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brendan-c/2c3d534e75176fdfa10609a9efeca99a to your computer and use it in GitHub Desktop.
Save brendan-c/2c3d534e75176fdfa10609a9efeca99a to your computer and use it in GitHub Desktop.
Wrap new lines
function wrapNewLines(targetSelector, wrapEl = 'span', wrapClass = 'new-line') {
const content = document.querySelectorAll(targetSelector)
content.forEach(section => {
let sectionWidth = section.getBoundingClientRect().width
let words = section.innerText.split(/( )/g)
section.innerHTML = ''
words.forEach(word => {
section.innerHTML += `<span>${word}</span>`
})
let lines = []
let line = []
let lineWidth = 0
let spans = section.querySelectorAll('span')
spans.forEach((span, i) => {
let spanWidth = span.getBoundingClientRect().width
if (lineWidth + spanWidth <= sectionWidth - 1) {
line.push(span)
lineWidth += spanWidth
} else {
lines.push(line)
line = []
lineWidth = 0
line.push(span)
lineWidth += spanWidth
}
})
if (line.length) lines.push(line)
let newLines = lines
.map(
line =>
`<${wrapEl} class=${wrapClass}>${line
.map(span => span.innerText)
.join('')}</${wrapEl}>`
)
.join('')
section.innerHTML = newLines
})
}
// Examples:
// wrapNewLines('.wrap-me')
// <span class='new-line'> ... </span>
// wrapNewLines('.wrap', 'div', 'line')
// <div class='line'> ... </div>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment