Core JavaScript

Change the Font for a Div Element

This JavaScript Reference section displays the code for an example program that shows how to change the font for a div element and add it as a child element. The font specification has five parts: style, variant, weight, size/line-height, and the font family. The style can be set to normal, italic, or oblique; the default value is normal. The variant can be set to normal or small-caps; the default is normal. The weight can be set to normal, bold, bolder, lighter, or multiples of 100 (100-900); the default is normal. The size/line-height can be set to xx-small, x-small, small, medium, large, x-large, xx-large, a size relative to the parent (smaller, larger, or a percentage), or a fixed size in units of px (pixels), pt (points), pc (picas), in (inches), mm (millimeters), or cm (centimeters). The size may be speccified with or without a line height. The font family can be set to successive list of comma-separated prefered options, the first available of which will be chosen by the browser. The family can be a specific font, like times, courier, arial, helvetica, georgia, palatino linotype, book antiqua, times new roman, arial black, impact, lucida sans unicode, tahoma, verdana, lucida console, or a generic font like serif, sans serif, cursive, fantasy, or monospace.

ChangeFont.html

<!DOCTYPE html>
<html>
<head>
    <title>XoaX.net's Javascript</title>
</head>
<body>
    <script type="text/javascript" src="ChangeFont.js"></script>
</body>
</html>

ChangeFont.js

var qBody = document.getElementsByTagName("body")[0];

var qNewDiv = document.createElement("div");
qNewDiv.style.backgroundColor = "#eedddd";
qNewDiv.style.border = "3px solid #A08080";
qNewDiv.style.padding = "15px";
qNewDiv.style.width = "600px";
qNewDiv.style.height = "200px";
qNewDiv.style.margin = "5px";
qNewDiv.style.color = "#504040";
qNewDiv.style.font = "normal 16px courier new";
qNewDiv.innerHTML = "For they reasoned unsoundly, saying to themselves,<br />" +
"&quot;Short and sorrowful is our life,<br />" +
"and there is no remedy when a man comes to his end,<br />" +
"and no one has been known to return from Hades.<br />" +
"Because we were born by mere chance,<br />" +
"and hereafter we shall be as though we had never been;<br />" +
"because the breath in our nostrils is smoke,<br />" +
"and reason is a spark kindled by the beating of our hearts.&quot;<br />" +
"(Wisdom 2:1-2 RSVCE)";
qBody.appendChild(qNewDiv);
 

Output

 
 

© 2007–2024 XoaX.net LLC. All rights reserved.