Get the width 'width' of a text?

1

We usually get the width width of a div or any other tag within the page.

How can you get the width of a plain text? For example:

Um texto

How do I know the width of this text in the JavaScript page?

  

It is not the size of the string, it is the width in pixels.

    
asked by anonymous 24.02.2018 / 01:59

3 answers

1

To get the width width of a text, you can wrap it in a span tag. span is an inline tag > that has no effect on the layout of the page. Soon the text would look like this:

<span>Um texto</span>

Now that we have the text inside a tag, it's easy to know the width that it occupies with the code:

console.log($("span").width());
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><span>Umtexto</span>

WithVanillaJS:

console.log(document.body.querySelector("span").offsetWidth);
<span>Um texto</span>
    
24.02.2018 / 04:49
2

Without being in some element, there is no way. My suggestion is to create a wrapper to store the text and then remove it.

var calculateTextWidth = function(text) {
    var span = document.createElement('span');
    span.innerText = text;

    document.body.appendChild(span);
    var width = span.offsetWidth;
    span.parentNode.removeChild(span);

    return width;
}

Calculating in an empty body and considering default browser styles.

calculateTextWidth('Um texto'); // 64px
    
24.02.2018 / 03:29
0

Look, I've seen that using clientWidth you can get the size of the element where the text is: Element.clientWidth - Web APIs | MDN

However, you have to set the position with Fixed with CSS.

var text;
var fs;
function capterWH(){
	var w = text.clientWidth+"px";
	var h = text.clientHeight+"px";
	document.getElementById("result").innerHTML = "Width: "+w+" - Height"+h;
}

function insertText(txt){
	text.innerHTML = txt;
}

function sizeTxt(o){
    if(o == "+"){fs = fs + 1;}
    if(o == "-"){fs = fs - 1;}
	text.style.fontSize = fs+"pt"
}

window.onload = function(){
   text = document.getElementById("Text");
   fs = parseInt(text.style.fontSize);
}
#Text
{
   position: fixed;
}
<i id="result">------------</i><br />
Insira o texto: <input type="text" onchange="insertText(this.value)" value="Um texto" /><input type="button" onclick="capterWH()" value="Tamanho em PX" /><br /><br />
<input type="button" onclick="sizeTxt('-')" value="Diminuir fonte" />
<input type="button" onclick="sizeTxt('+')" value="Aumentar fonte" /><hr />
<p id="Text" style="font-size:12pt;">Um texto</p><br />
    
24.02.2018 / 03:13