Subaz Subaz - 22 days ago 6
Javascript Question

If.. Then in javascript

I want to change the font size of a text depending on the current font size.


On clicking the text,

If font size = 35, change it to 12

else if font size = 12, change it to 35

<!DOCTYPE html>
<h2>What Can JavaScript Do?</h2>

<p id="demo" onclick="myFunction()">Click me.</p>

function myFunction() {
if (document.getElementById('demo').style.fontSize='35px') {
} else if(document.getElementById('demo').style.fontSize='12px') {



It changed it 12, but never changes back to 35. What did I miss here?

Answer Source

You have assignment in the if statement. You need to use not =, but == or better ===.

Also one note, if the font-size is defined in the css, it may return to you an empty string for the first time. In this case you need to use window.getComputedStyle to get the font-size.

function myFunction() {
      const element = document.getElementById('demo');
      const fontSize = window.getComputedStyle(element, null).getPropertyValue('font-size');

      if (fontSize === '35px') { = '12px';
      } else if(fontSize === '12px') { = '35px';
p#demo {
   font-size: 12px;
<h2>What Can JavaScript Do?</h2>
<p id="demo" onclick="myFunction()">Click me.</p>