Get font size in HTML

3

I need to get the information from the font that is set up in the HTML tag with JQuery.

I know that to get the size of the font-size just use:

css:

p {font-size: 12px;}

JS:

var tamanho = $("p").css('font-size');

The question is, how can I get the font size that is set up in HTML this way:

html {font: normal 16px / 25px 'Montserrat';}

I thought of several ways but could not find a solution. Is it possible?

JQuery used: link

    
asked by anonymous 06.10.2017 / 20:39

3 answers

6

Equivalent to bfavaretto but with compatibility for legacy browsers:

function getStyle(elem, prop)
{
    if (elem.currentStyle) { //IE8
        prop = prop.replace(/-([a-z])/gi, function (value) {
            return value.toLowerCase();
        });
        
        return elem.currentStyle[prop];
    } else if (window.getComputedStyle) {//Navegadores modernos
        prop = prop.replace(/([A-Z])/g, '-$1').toLowerCase();
        
        return window.getComputedStyle(elem, null).getPropertyValue(prop);
    }
}

console.log(getStyle(document.getElementById('Teste'), 'font-size'));
console.log(getStyle(document.getElementById('Teste'), 'fontSize'));
html {font: normal 16px / 25px 'Montserrat';}
<p id="Teste">Foo bar</p>

Extra

Even using jQuery.css or getStyle there is a very important detail, in different browsers can occur not returning in pixels (% with%), can return values as px or em .

To remove these characters I recommend using pt with and do not use .replace without checking if the value is parseInt or something else (as empty), otherwise it can give problem, do so:

tamanhoFonte = $(elemento).css('font-size'); //ou getStyle(elemento, 'font-size')
tamanhoFonte = tamanhoFonte.replace(/[a-z]/gi, ""); //Remove letras, mas mantem pontos e numeros
tamanhoFonte = tamanhoFonte ? parseInt(tamanhoFonte) : 0;
    
06.10.2017 / 20:50
7

With the global getComputedStyle function:

var elemento = document.getElementById('elemento'); // ou $('#elemento')[0]
var estilos = window.getComputedStyle(elemento, null);
var tamanho = estilos.getPropertyValue('font-size');

console.log(tamanho)
html {font: normal 18px / 25px 'Montserrat';}
<p id="elemento">
sfsadas fasda sdas dasd asdas da d 
</p>
    
06.10.2017 / 20:47
5

Likewise:

var tamanho = $("html").css('font-size');

And if you want to remove "px" to work with the integer:

var tamanho = parseInt(tamanho.replace("px",""));
    
06.10.2017 / 20:50