JavaScript frequently involves establishing references to elements on your page and then getting and setting their properties to guide what your program does. One of the most common ways of creating a reference to a specific page element is by using the 'getElementById()' function that is attached to the document of any page that you're on. Moreover, you can assign that reference to a variable for ongoing use, so that once you have established such a reference, it is very easy to set and get various properties on the item throughout the life of your script (which is essentially the life of the page). Which properties can be get or set may vary widely, and you'll eventually come to know what can and cannot be get or set. Let's take a look at a simple example of a button that, when clicked, looks itself up and alerts its own 'tagName' (a property known to JavaScript about every element on your page... in this case, it will be "BUTTON"):
Once a reference to an element has been established, any number of properties can be manipulated, including its style, src (if it's an image or script, for example), title (the little pop-up mouse pointer text), and even its HTML structure. Available to almost all block elements on an HTML page, the '.innerHTML' property can be set or retrieved by setting or getting its built-in 'innerHTML' property. When retrieved, it provides a string of HTML representing what is currently within that element. For example, if you have a DIV containing a TABLE tag, the ".innerHTML" of the DIV will contain something like "[[table]] [[/table]]". If, in turn, you reset the innerHTML of the DIV to "[[p]]Hello[[/p]]", then that table will disappear on the page, and it will be replaced by a paragraph containing the text "Hello". This 'innerHTML' property will be very useful in future examples throughout these tutorials, so let's take a look at an example that makes use of it now...
...
Title | Genre |
---|---|
Dawn of the Dead | Horror, Zombie |
Shaun of the Dead | Comedy, Zombie |
Did you notice what's interesting about the last line of the code? The call to 'document.getElementById()' works right after modifying the innerHTML of the DIV. It turns out that once you change the innerHTML of an element in your page, the DOM is appropriately updated to reflect that, and vice versa. So once you've written the HTML for a table with that ID into your DIV, subsequent lines of code can use 'document.getElementById()' to reference that new element!
Recommended next: Object-Oriented Programming in JavaScript