Font size isn't getting changed

I want to change the font size of an element periodically but it isn't working.

I tried console.log() to get the size of the font but it returned some info in curly brackets. (I'm fairly new to JavaScript so I don't know if that is something which is expected). I tried looking up the documentation but even then it doesn't work.

JavaScript:

var text = document.getElementById("main");
var x = setInterval(incFont, 100);
console.log(document.getElementById("main").style.fontSize);
var size = parseInt(document.getElementById("main").style.fontSize, 10);

function incFont()
{
    size = size + 1;
    document.getElementById("main").style.fontSize = "" + size;
}

HTML:

<p id="main">
    Text-Growing
</p>
<script src="function.js"></script>

Output of console.log:

{"notifyType":"consoleItemLog","message":{"message":"","styles":"","hasFormatString":true,"fileUrl":"file:///D:/170911092/Lab%203/function.js","lineNumber":3,"columnNumber":1}}

1 answer

  • answered 2019-08-13 03:40 Dave Anderson

    Without some units, see ways to specify the font size, you cannot update style.fontSize.

    The object returned from document.getElementById("content").style is CSSStyleDeclaration, to set properties you can also use setProperty().

    The .fontSize style name is actually font-size so either of the following will update the CSS;

    document.getElementById("main").style.fontSize = '12px';
    document.getElementById("main").style.setProperty('font-size','12px');