To underline a paragraph using JavaScript, we can simply use the style textDecoration property.

document.getElementById("p1").style.textDecoration = "underline";

Let’s say we have the following HTML:

We will change this text to be undelined.


If we want to add an underline to the paragraph, we will use the textDecoration property in the following JavaScript code.

document.getElementById("p1").style.textDecoration = "underline";

If we wanted to change the font size of the paragraph, we could do that easily by targeting the fontSize property.

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

Adding an Underline to a Paragraph in JavaScript with a Click

To underline a paragraph using JavaScript, we can target the style textDecoration property with a click event.

Let’s say we have the following HTML and we want to add an underline to the first paragraph only.

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.

Underline first text

We can utilize both the Style textDecoration property of #p1 along with an onclick event to add an underline to the first line of text.

Here is the JavaScript code:

function setUnderline() {
  document.getElementById("p1").style.textDecoration = "underline";
}

The final code and output for this example of how underline 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.

Underline first text

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.

Underline first text



Hopefully this article has been useful for you to understand how to add an underline to a paragraph in JavaScript.

Categorized in:

JavaScript,

Last Update: May 3, 2024