To change the font size of a paragraph using JavaScript, we simply use the style fontSize property.

document.getElementById("p1").style.fontSize = "12px";

Let’s say we have the following HTML:

We will change the font size of this text.

If we want to change the font size of the paragraph to “12px”, we will use the fontSize property in the following JavaScript code.

document.getElementById("p1").style.fontSize = "12px";

If we wanted to underline the paragraph, we could do that easily by targeting the textDecoration property.

We can change many styles using JavaScript by targeting the style properties of an element.

Using JavaScript to Change the Font Size of Text with a Click

To change the font size of text using JavaScript, we can target the style fontSize property with a click event.

Let’s say we have the following HTML and we want to change the font size of the first paragraph to make it smaller.

The Programming Expert

Code Snippets to Help You Solve Your Programming Headaches Fast

Find Solutions for Your Programs in Python, PHP, HTML, SAS, JavaScript and more.

Change font size

We can utilize both the Style fontSize property of #p1 along with an onclick event to change the font size of the first line of text.

Here is the JavaScript code:

function clickFunction() { 
  document.getElementById("p1").style.fontSize = "32px";
}

The final code and output for this example of how to change the font size of a paragraph using JavaScript is below:

Code Output:

The Programming Expert

Code Snippets to Help You Solve Your Programming Headaches Fast

Find Solutions for Your Programs in Python, PHP, HTML, SAS, JavaScript and more.

Change font size

Full Code:

The Programming Expert

Code Snippets to Help You Solve Your Programming Headaches Fast

Find Solutions for Your Programs in Python, PHP, HTML, SAS, JavaScript and more.

Change font size

Hopefully this article has been useful for you to understand how to use JavaScript to change the font size of some text.

Categorized in:

JavaScript,

Last Update: February 26, 2024