Skip to content

Instantly share code, notes, and snippets.

@vincentorback
Created January 11, 2023 19:36
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 vincentorback/a2d684dabd3210241a6c23b25d9890c4 to your computer and use it in GitHub Desktop.
Save vincentorback/a2d684dabd3210241a6c23b25d9890c4 to your computer and use it in GitHub Desktop.
Check if textNode has text on multiple lines
// console.log(getTextLines(querySelector('span')))
// returns number of lines
function collapseWhiteSpace(value) {
return value.trim().replace(/\s+/g, ' ')
}
function getTextLines(textNode) {
if (textNode.nodeType !== 3) {
return false // Only text nodes allowed
}
textNode.textContent = collapseWhiteSpace(textNode.textContent)
var textContent = textNode.textContent
var range = document.createRange()
var lines = []
var lineCharacters = []
// Iterate over every character in the text node.
for (var i = 0; i < textContent.length; i++) {
// Set the range to span from the beginning of the text node up to and
// including the current character (offset).
range.setStart(textNode, 0)
range.setEnd(textNode, i + 1)
// At this point, the Range's client rectangles will include a rectangle
// for each visually-rendered line of text. Which means, the last
// character in our Range (the current character in our for-loop) will be
// the last character in the last line of text (in our Range). As such, we
// can use the current rectangle count to determine the line of text.
var lineIndex = range.getClientRects().length - 1
// If this is the first character in this line, create a new buffer for
// this line.
if (!lines[lineIndex]) {
lines.push((lineCharacters = []))
}
// Add this character to the currently pending line of text.
lineCharacters.push(textContent.charAt(i))
}
// At this point, we have an array (lines) of arrays (characters). Let's
// collapse the character buffers down into a single text value.
lines = lines.map(function operator(characters) {
return collapseWhiteSpace(characters.join(''))
})
return lines.length
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment