function truncateNode(node, length) {
if (node instanceof Text) {
if (node.length > length) {
node.textContent = node.substringData(0, length);
}
} else if (nodeDeepLength(node) > length) {
let deleting = false;
for (let child of node.childNodes) {
if (deleting) {
child.remove();
continue;
} else {
let childLen = nodeDeepLength(child);
if (childLen > length) {
truncateNode(child, length);
deleting = true;
} else {
length -= childLen;
}
}
}
}
return node;
}