JavaScript 101: Week Four - DOM DOM DOM!
“What happened to Week 3” you ask. “Hey - aren’t we on Week 5 already?”
Kindly STFU, Dear Reader.
I have allowed myself to fall a little behind with the course ( <—- see how good I am at understatement?) y’see, and I’m going to catch myself up in descending order of difficulty. Week 3 was a pain, Week 4 a relative cinch. To the blogmobile!
In contrast to Week 3, the effect of which on my mind was like drinking a Pan-Galactic Gargleblaster without the chaser, Week 4 wasn’t too hard to comprehend.
Perhaps because I taught myself how to use InDesign a few years ago, which involved getting familiar with the very similar way that it structures page layouts to allow the user to import content from an XML document into a layout automatically, but getting the way that the Document Object Model works wasn’t too tricky. Having a little experience with syntax trees in introductory linguistics didn’t hurt either ;)
Essentially, the DOM is a “model” or representation of HTML page as a hierarchical “tree” of nodes. Each node has a few different properties, just like an object in JavaScript, and they can be manipulated in basically the same way. By manipulating the nodes in the DOM, you manipulate the page.
This week’s Questions for Reflection (and my answers):
What are the roles of “name” and “id” atributes in HTML tags? What is an appropriate use of both?
They both serve to allow direct access to a particular element, but beyond that they serve different function and are slightly different. “name” is used more to annotate form data for server-side applications. It need not be unique. “id” is used more for client-side applications and scripting, and each ID has to be unique.
Which pointers does each node in the DOM tree typically have?
Each node in the DOM tree has “pointers” to the node above it in the hierarchy (‘parentNode’), all of its subsidiary/child nodes (‘childNode’, returns an array, as there can be more than one), it’s first subsidiary (‘firstChild’), it’s last (‘lastChild’), and next or previous nodes at the same level in the hierarchy (‘nextSibling’ or ‘previousSibling’).
Given a node object from a DOM tree, how do we determine if it is a text node or a regular node?
As far as I can see so far, there are two ways to do this. The “nodeName” property, and the “nodeType” property. If the node is a text node, “nodeName” will return “#text” and “nodeType” will return “3”. Please correct me if I’m wrong.
Okay, that’s questions out of the way. Stand by for the answers to Week 4 exercises.