0

I'm trying to calculate the number of characters that fits in one line of a div and trim off the rest although text-overflow is an option I rather calculate the length of the string that fits in it properly. Is the font-size of a character almost equal to it's width, if not how do you calculate it's width including the text spacing and the width of a white space.

P.S. - Before flagging this question, do know I've went through most of the questions and answers and none of them were satisfactory.

3

1 Answer 1

0

One way I would do it is to check if there's enough space left in the div. To do this, you would need to create an identical div and slowly remove one character from the cloned div until the original div is bigger or equal in width to the cloned div.

divClone.textContent = text document.body.appendChild(divClone) while(divClone.clientHeight > originalDiv.clientHeight) { divClone.textContent = divClone.textContent.substring(0, divClone.textContent.length-1) } originalDiv.textContent = divClone.textContent 

You can then delete the cloned div when it's done

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.