Changing text size with JavaScript using an ID selector

The following code is placed immediately before the closing </body> tag. The script works by manipulating the DOM, so placing it at the end of the file allows the DOM to complete before the script can run:


function changeText(){
   document.getElementById("box").style.fontSize = "125%";

function changeBack(){
   document.getElementById("box").style.fontSize = "100%";

var change = document.getElementById("change");
change.onclick = changeText;

var back = document.getElementById("back");
back.onclick = changeBack;


The above example uses two functions, one to make the change and one to change it back. This isn't the most efficient way of doing it but it is the simplest.

The object (element) you want to change is identified by an ID. Remember, this is unique to that object. In this example, the element containing the code above has been given the ID "box" and the opening tag looks like this: <pre id="box">.

Each script is run by clicking an element which has an onclick event handler. In this case it's two spans with an id and styled to look like a button.

Try the "buttons" below to see what happens.

Increase text sizeReset