I have a quite problematic task, I'd like to calculate the width
of the widest word in my div, so I can set a min-width
with javascript on a resizable div.
I tried working on something, I managed to get the longest word, unfortunately not the widest and I also failed to get his width.
Fiddle : https://jsfiddle.net/Lindow/oayddb8w/3/
JavaScript :
function longestWord(string) {
var str = string.split(" ");
var longest = 0;
var word = null;
for (var i = 0; i < str.length; i++) {
if (longest < str[i].length) {
longest = str[i].length;
word = str[i];
}
}
return word;
}
var test = document.getElementById("Test");
var longest_word = longestWord(test.innerHTML); // test.innerHTML == 'dofkdspakdasdsakd,'
var width = (longest_word.clientWidth + 1) + "px"; // 'NaNpx'
alert(longest_word);
HTML :
<div id="Test">
abcdefghijklmn, opqrstuvwxyzAB
ddoafkpdsfk,
dsapdlasèd. CDEFGHIJKLMNO,
dofkdspakdasdsakd, PQRSTUVWXYZ
</div>
Any suggestion ? The issue here is not to get the width of all the words, but just the widest word in a bunch of text, which change the problematic.
UPDATE :
This post helped me : Find the width of the widest word in the html block
I have to put every word in <span>
tag and check through them which one is the widest according their fontFamily and fontSize.