Consider the following steps:
- Explore the structure of the editor by accessing its
body
property.
- Identify longer words within the content.
- Use the DOM Range API to wrap longer words in a span element.
Below is a basic implementation that specifically targets direct children of the BODY element:
function applyEllipsis(editor, node) {
// iterate through child nodes
for (var i = 0; i < node.childNodes.length; i++) {
var child = node.childNodes[i];
// process only text nodes (nodeType == 3)
if (child.nodeType == 3) {
// extract the text content of the node
var text = child.nodeValue;
// split the text into words
var words = text.split(" ");
var position = 0;
// iterate through the words
for (var i = 0; i < words.length; i++) {
var word = words[i];
// check the length of the word
if (word.length > 4) {
var range = editor.createRange();
// define the range to encompass the word
range.setStart(child, position + 1);
range.setEnd(child, position + 1 + word.length);
// create a span element to wrap the word
var span = editor.document.createElement("span");
span.style.display = "inline-block";
span.style.width = "50px";
span.style.overflow = "hidden";
span.style.whiteSpace = "nowrap";
span.style.verticalAlign = "bottom";
span.style.textOverflow = "ellipsis";
span.title = word;
// wrap the word with the span element
range.surroundContents(span);
child = span.nextSibling;
position = 1;
} else {
position += word.length;
}
}
}
}
}
For a demonstration, check out the live demo here: