|
|
ArticleNodeEssentials
HOWTO deal with DOM nodes (goog.dom.NodeType, goog.dom.getNextElementNode, goog.dom.isNodeLike)
| Español | 日本語 | Français |
| Home | Articles DOM |
This article introduces a few constants and utility functions for dealing with DOM nodes.
The code
/**
* Enumeration for DOM node types (for reference)
* @enum {Number}
*/
goog.dom.NodeType = {
ELEMENT: 1,
ATTRIBUTE: 2,
TEXT: 3,
CDATA_SECTION: 4,
ENTITY_REFERENCE: 5,
ENTITY: 6,
PROCESSING_INSTRUCTION: 7,
COMMENT: 8,
DOCUMENT: 9,
DOCUMENT_TYPE: 10,
DOCUMENT_FRAGMENT: 11,
NOTATION: 12
};
/**
* Returns the first child node that is an element.
* @private
* @param {Node} node The node to get the next element from
* @param {Boolean} forward Whether to look forwards or backwards
* @return {Element}
*/
goog.dom.getNextElementNode_ = function(node, forward) {
while (node && node.nodeType != goog.dom.NodeType.ELEMENT) {
node = forward ? node.nextSibling : node.previousSibling;
}
return node;
};
/**
* Whether the object looks like a DOM node
* @param {Object} obj
* @return {Boolean}
*/
goog.dom.isNodeLike = function(obj) {
return goog.isObject(obj) && obj.nodeType > 0;
};The code walkthrough
First we define an enumeration of the different node types, such as ELEMENT or ATTRIBUTE. These are not random; they are the values defined in the DOM specification and are returned by properties like node.nodeType.
goog.dom.NodeType = {
ELEMENT: 1,
ATTRIBUTE: 2,
TEXT: 3,
CDATA_SECTION: 4,
ENTITY_REFERENCE: 5,
ENTITY: 6,
PROCESSING_INSTRUCTION: 7,
COMMENT: 8,
DOCUMENT: 9,
DOCUMENT_TYPE: 10,
DOCUMENT_FRAGMENT: 11,
NOTATION: 12
};If you need to do a sanity check to determine that a variable is actually a DOM node, the goog.dom.isNodeLike function can do that:
goog.dom.isNodeLike = function(obj) {
return goog.isObject(obj) && obj.nodeType > 0;
};Further reading
Sign in to add a comment
