w3resource

JavaScript: Modify paragraph text style through javascript code using button

JavaScript DOM: Exercise-1 with Solution

Style Paragraph

Here is a sample html file with a submit button. Now modify the style of the paragraph text through javascript code.

Sample HTML file:

<!DOCTYPE html>
<html><head>
<meta charset=utf-8 />
<title>JS DOM paragraph style</title>
</head> 
<body>
<p id ='text'>JavaScript Exercises - w3resource</p> 
<div>
<button id="jsstyle"
onclick="js_style()">Style</button>
</div>
</body>
</html>

Tips: Clicking on the button the font, font size, and color of the paragraph text will be changed.

Sample Solution:

HTML Code:

<!-- Declaration of HTML document type -->
<!DOCTYPE html>
<!-- Start of HTML document -->
<html>
<head>
<!-- Declaring character encoding -->
<meta charset=utf-8 />
<!-- Setting title of the document -->
<title>JS DOM paragraph style</title>
</head> 
<!-- Start of body section -->
<body>
<!-- Creating a paragraph element with id 'text' -->
<p id ='text'>JavaScript Exercises - w3resource</p> 
<!-- Creating a division element -->
<div>
<!-- Creating a button element with id 'jsstyle' and onclick event -->
<button id="jsstyle" onclick="js_style()">Style</button>
</div>
<!-- End of body section -->
</body>
<!-- End of HTML document -->
</html>

JavaScript Code:

// Function declaration for js_style
function js_style() 
{
    // Setting font size using JavaScript
    text.style.fontSize = "14pt";
    // Setting font family using JavaScript
    text.style.fontFamily = "Comic Sans MS";
    // Setting text color using JavaScript
    text.style.color = "green";
}

Output:

javascript-dom-exercise-1

Flowchart:

Flowchart: JavaScript - Modify paragraph text style through javascript code using button.

Live Demo:

See the Pen javascript-dom-exercise-1 by w3resource (@w3resource) on CodePen.


For more Practice: Solve these Related Problems:

  • Write a JavaScript function that toggles the paragraph style between two distinct style sets each time a button is clicked.
  • Write a JavaScript function that randomly selects font family, font size, and color from predefined arrays and applies them to the paragraph.
  • Write a JavaScript function that applies a gradient background effect to the paragraph by dynamically setting its CSS background-image property.
  • Write a JavaScript function that reads a CSS class name from a dropdown menu and applies that class to the paragraph element on button click.

Improve this sample solution and post your code through Disqus.

Previous: JavaScript DOM Exercises
Next: Write a JavaScript function to get the values of First and Last name of the following form.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.