Dynamically edit font styling of HTML content via JavaScript

The Document Object Model (DOM) allows for dynamic styling because it makes all HTML elements and attributes readily accessible using JavaScript. Here is a simple demo of how powerful this technology can be:

Demo
Hello world!








Here is the JavaScript code that makes all this possible:

<div id="dynamicContent">Hello world!</div>
<input type="button" onClick="document.getElementById('dynamicContent').style.fontWeight = 'bolder';" value="Bold">
<input type="button" onClick="document.getElementById('dynamicContent').style.fontWeight = 'lighter';" value="Lighter">
<input type="button" onClick="document.getElementById('dynamicContent').style.fontStyle = 'normal';" value="Normal">
<input type="button" onClick="document.getElementById('dynamicContent').style.fontStyle = 'italic';" value="Italic">
<input type="button" onClick="document.getElementById('dynamicContent').style.fontFamily = 'courier';" value="Courier">
<input type="button" onClick="document.getElementById('dynamicContent').style.fontFamily = 'roman';" value="Times Roman">

In this example, we use the JavaScript onClick event handler to dynamically change the content styling of the text within the div tags. To access the div object, we use the getElementById() function and pass over the div id which is, dynamicContent in this case, as the argument. Once we have access to the div element, we have access to all the styles that are associated with it.

There are a myriad of things that you can change such as font size, font weight, font face, font color, background color, borders and much much more.

Published by

Allen Liu

Building websites is a passion of mine. During the course of my work, I have created some snippets of code that I hope will prove useful to other developers.

Leave a Reply

Your email address will not be published. Required fields are marked *