PPK on JavaScript: The DOM - Part 1/Page 5 | WebReference

PPK on JavaScript: The DOM - Part 1/Page 5

[previous] [next]

PPK on JavaScript: The DOM - Part 1

C: Node information

Every node has a few properties that contain a bit of information about the node. They are nodeName, nodeValue, nodeType, and tagName.


nodeName is the most useful property. Unsurprisingly, it contains the name of the node. The name of an element node is always the tag name, the name of an attribute node is always the attribute name, the name of a text node is always #text, and the name of the document node is always #document.

One caveat: nodeName contains the UPPERCASE tag name of an HTML element, even if you used lowercase in your HTML.

As an example, take this function from Usable Forms. It fires whenever the user clicks anywhere in the document or changes a select box, and I need to find out if this action took place on a form field or a label:

First the function accesses the event target, as we discussed in 7F. Then it checks if the target is a select and the event type is 'change', or if the target is an input that has a rel attribute. If neither is true, the function ends. (We discussed this if statement in detail in 5H.) For both checks I use nodeName.


On text nodes, nodeValue contains the actual text:

On attribute nodes, nodeValue contains the attribute value. It is not available on document and element nodes.

In Sandwich Picker, I use nodeValue to find the sandwich name:

This function goes through all <tr>s in the start table, takes their <td>s, and then accesses the first child of the second <td>, which always contains the sandwich name. It then takes its nodeValue, sets it to lowercase to be safe, and stores it in the productName property of the <tr> object.

Reading out the content of text nodes is the only practical application of nodeValue.


nodeType Table

There are many more node types, but they aren't important in Web development.

We saw an example of nodeType's use in 7F. In Safari, the target of an event might be a text node instead of an element node. I use nodeType to find out if this is the case, and if so, I redirect the target to the text node's parent:


tagName also contains the tag name of element nodes, but it is not available on any other node type. Since it contains the same information as nodeName but is less versatile, I never use tagName.

[previous] [next]