Take a look at this awesome website for the City of New York:
There’s so much we can do! Click on the arrows at the left and right to see other top headlines! Click on “Select Language” and see a list of all the languages available for translating the page! Hover over “NYC Resources” or “311″ or “Office of the Mayor” or any of the other links across the navigation bar, and watch their background color change from white to black (and text color from black to white)!
But the main HTML for the website, which defines the elements on the page, and the CSS, which defines the styling for those elements, are merely more than text files when they are sent to the web browser. The browser is also sent a separate file in Javascript (or a similar dynamic language) which defines the dynamic behavior for the page. However, with the HTML in its native form–as a hypertext file–the Javascript file has a very limited ability to be able to interpret the HTML and know which method should be done on which part of the page.
So how do the HTML and Javascript communicate?
The answer lies in the Document Object Model, or DOM. When the web browser receives the website it requested from the server, it takes the lowly HTML file and converts each element into an object, which holds the attributes and values of that element as key-value pairs, and also holds information like the parent of the element (was it nested within another HTML element?) and its position among its “siblings” (is it the second element of a bulleted list? the fifth?).
The browser stores the DOM and then is able to understand Javascript methods that reference particular elements.

Image source: webstepbook.com
The example above shows how we would change the image that is displayed as “icon01” on the page. The HTML file, when stored in the DOM, can be referenced with the name “document”. The built-in function getElementById is called on document, and the id “icon01″, which uniquely refers to the octopus image, is passed in. The result, which is a DOM element object, is saved with the variable name “icon”. Then, the “src” property of that object is set to the new image “kitty.gif”, replacing the octopus picture with a kitty picture. When exactly this change would occur (when the user clicks on a specific place on the page, or immediately after the page loads, or 5 seconds after the page loads) would be dependent on which Javascript function we call on that element (which is not shown in the example).
With the DOM in place, the HTML and Javascript are able to work together to produce a happier and more dynamic website.



This is pretty verbose. Wouldn’t it be great if we could just iterate through each of the attributes, setting the class instance variable whose name matches the hash’s key equal to value at that hash key? Here’s the idea of what we want to do:










