Storing DOM and Functions in Variables

EasyProgramming.net - Learn how, why, and when to store DOM elements and functions into variables.

by Nazmus Nasir

HTML

<!-- JavaScript Variables and typeof() - DOM elements & Functions - #6 -->
<p>
  Variables can also be assigned other types of values such as DOM elements and Functions. 
<br />More Tutorials at <a href="http://www.easyprogramming.net">EasyProgramming.net</a>
</p>

  <div id="title">
    JavaScript Variables
  </div>

JavaScript

//DOM element - listed as an object
var title = document.getElementById("title");
//console.log(title);
console.log("title is of type " + typeof(title));

//Makes life easier beacuse it allows you to bypass the document.getElementById() piece 
title.style.color = 'red';
title.style.fontSize = "25px";
title.innerText = "This is my JavaScript code";

//Function type - can store entire functions in variables
var added = function(){ return 5+5;  };
console.log("added is of type " +typeof(added));
//console.log(added);
//console.log(added());