Open In App

JavaScript Program to set the Font to be Displayed in Small Capital Letters

In this article, we will set the font to be displayed in small capital letters with JavaScript. To change the font to be displayed in small capital letters dynamically, we use HTML DOM Style font-variant property. CSS provides a straightforward way to apply small caps to text, there may be situations where you need to dynamically set the font to small caps using JavaScript. Let’s discuss two approaches to achieve this.

Approaches to Set the Font in Small Capital Letters

Approach 1: Modifying the CSS font-variant property

The font-variant CSS property allows us to specify variations in the font’s appearance, including the use of small caps. We can dynamically modify the font-variant property of an HTML element using JavaScript to apply small caps to the text.



Syntax:

element.style.fontVariant = "small-caps";

Example: This example shows the use of the above explained approach.




<!DOCTYPE html>
<html>
  
<body style="text-align: center">
    <h1 style="color: green">GeeksforGeeks</h1>
    <h2>
        How to set the font of<br />a text in small
        letters using JavaScript?
    </h2>
    <p id="sudo">WELCOME TO GEEKSFORGEEKS</p>
    <br />
    <script>
        const element = 
                  document.getElementById("sudo");
        element.style.fontVariant = "small-caps";
    </script>
</body>
  
</html>

Output:



Approach 2: Modifying the CSS text-transform property

By setting the text-transform property to "lowercase", we can convert the text to lowercase and will produce the desired result.

Syntax:

element.style.textTransform = "lowercase"

Example: This example shows the use of the above-explained approach.




<!DOCTYPE html>
<html>
  
<head>
    <title>
          How to set the font of a text in small 
          letters using JavaScript?
      </title>
    <style>
        #sudo {
            text-transform: lowercase;
        }
  
        .small-caps {
            font-variant: small-caps;
        }
    </style>
</head>
  
<body style="text-align: center;">
    <h1 style="color: green">
          GeeksforGeeks
      </h1>
    <h2>
          How to set the font of<br>a text in 
          small letters using JavaScript?
      </h2>
    <p id="sudo">WELCOME TO GEEKSFORGEEKS</p>
    <br>
    <button type="button" onclick="myGeeks()">
          lick to change
      </button>
  
    <script>
        function myGeeks() {
            const element = 
                      document.getElementById("sudo");
            element.classList.toggle("small-caps");
        }
    </script>
</body>
  
</html>

Output:


Article Tags :