
Using the Document Object Model, we gain access to any elements that the webpage contains. Elements such as divs are suddenly at our full disposal. Today, I’m going to show you how to take control of these elements (first the elements, then the world! *evil laugh*).
We’re going to start out by selecting an element that has been assigned a specific id. Doing this will only return one element to us, as an id may only be used once. To do this, we’ll be using the getElementById(). With this function, if no element is found, it will return null. Let’s look at an example of where we select a div and change the text colour of it.
[code='javascript']document.getElementById('text').style.color = #CCCCCC;[/code]
Notice how Javascript and the DOM work in a nested manner. We start with the main document branch, then move down onto an element branch, creek our way onto the style branch and finally end up on the color twig. Envisioning the Document Object Model as a tree with branches (and branches on those branches, etc) is probably the easiest way to understand it.
The Document Object Model is very powerful, and understanding it will be key to getting a firm grasp on Javascript. If you don’t quite understand it, don’t fret, we’ll be continuing on with it for a couple more posts. You’ll have plenty of more chances to wrap your head around the concept.
PS: I’m attempting to keep my posts a bit shorter and focused on a single topic, in hopes of keeping more people’s attention. Let me know what you think.




