// Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Copyright 2006 Google Inc. All Rights Reserved. /** * @fileoverview Utilities for manipulating the browser's Document Object Model * Inspiration taken *heavily* from mochikit (http://mochikit.com/). * * If you want to do extensive DOM building you can create local aliases, * such as:<br> * var $DIV = goog.bind(goog.dom.createDom, goog.dom, 'div');<br> * var $A = goog.bind(goog.dom.createDom, goog.dom, 'a');<br> * var $TABLE = goog.bind(goog.dom.createDom, goog.dom, 'table');<br> * * You can use {@link goog.dom.DomHelper} to create new dom helpers that refer * to a different document object. This is useful if you are working with * frames or multiple windows. * */ // TODO: Rename/refactor getTextContent and getRawTextContent. The problem // is that getTextContent should mimic the DOM3 textContent. We should add a // getInnerText (or getText) which tries to return the visible text, innerText. goog.provide('goog.dom'); goog.provide('goog.dom.DomHelper'); goog.provide('goog.dom.NodeType'); goog.require('goog.array'); goog.require('goog.dom.TagName'); goog.require('goog.dom.classes'); goog.require('goog.math.Coordinate'); goog.require('goog.math.Size'); goog.require('goog.object'); goog.require('goog.string'); goog.require('goog.userAgent'); /** * @define {boolean} Whether we know at compile time that the browser is in * quirks mode. */ goog.dom.ASSUME_QUIRKS_MODE = false; /** * @define {boolean} Whether we know at compile time that the browser is in * standards compliance mode. */ goog.dom.ASSUME_STANDARDS_MODE = false; /** * Whether we know the compatibility mode at compile time. * @type {boolean} * @private */ goog.dom.COMPAT_MODE_KNOWN_ = goog.dom.ASSUME_QUIRKS_MODE || goog.dom.ASSUME_STANDARDS_MODE; /** * 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 }; /** * Gets the DomHelper object for the document where the element resides. * @param {Node|Window} opt_element If present, gets the DomHelper for this * element. * @return {!goog.dom.DomHelper} The DomHelper. */ goog.dom.getDomHelper = function(opt_element) { return opt_element ? new goog.dom.DomHelper(goog.dom.getOwnerDocument(opt_element)) : (goog.dom.defaultDomHelper_ || (goog.dom.defaultDomHelper_ = new goog.dom.DomHelper())); }; /** * Cached default DOM helper. * @type {goog.dom.DomHelper} * @private */ goog.dom.defaultDomHelper_; /** * Gets the document object being used by the dom library. * @return {!Document} Document object. */ goog.dom.getDocument = function() { return document; }; /** * Alias for getElementById. If a DOM node is passed in then we just return * that. * @param {string|Element} element Element ID or a DOM node. * @return {Element} The element with the given ID, or the node passed in. */ goog.dom.getElement = function(element) { return goog.isString(element) ? document.getElementById(element) : element; }; /** * Alias for getElement. * @param {string|Element} element Element ID or a DOM node. * @return {Element} The element with the given ID, or the node passed in. */ goog.dom.$ = goog.dom.getElement; /** * Looks up elements by both tag and class name, using browser native functions * ({@code querySelectorAll}, {@code getElementsByTagName} or * {@code getElementsByClassName}) where possible. This function * is a useful, if limited, way of collecting a list of DOM elements * with certain characteristics. {@code goog.dom.query} offers a * more powerful and general solution which allows matching on CSS3 * selector expressions, but at increased cost in code size. If all you * need is particular tags belonging to a single class, this function * is fast and sleek. * * @see goog.dom.query * * @param {?string} opt_tag Element tag name. * @param {?string} opt_class Optional class name. * @param {Element} opt_el Optional element to look in. * @return { {length: number} } Array-like list of elements (only a length * property and numerical indices are guaranteed to exist). */ goog.dom.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) { return goog.dom.getElementsByTagNameAndClass_(document, opt_tag, opt_class, opt_el); }; /** * Helper for {@code getElementsByTagNameAndClass}. * @param {!Document} doc The document to get the elements in. * @param {?string} opt_tag Element tag name. * @param {?string} opt_class Optional class name. * @param {Element} opt_el Optional element to look in. * @return { {length: number} } Array-like list of elements (only a length * property and numerical indices are guaranteed to exist). * @private */ goog.dom.getElementsByTagNameAndClass_ = function(doc, opt_tag, opt_class, opt_el) { var parent = opt_el || doc; var tagName = (opt_tag && opt_tag != '*') ? opt_tag.toLowerCase() : ''; // Prefer the standardized (http://www.w3.org/TR/selectors-api/), native and // fast W3C Selectors API. However, the version of WebKit that shipped with // Safari 3.1 and Chrome has a bug where it will not correctly match mixed- // case class name selectors in quirks mode. if (parent.querySelectorAll && (tagName || opt_class) && (!goog.userAgent.WEBKIT || goog.dom.isCss1CompatMode_(doc) || goog.userAgent.isVersion('528'))) { var query = tagName + (opt_class ? '.' + opt_class : ''); return parent.querySelectorAll(query); } // Use the native getElementsByClassName if available, under the assumption // that even when the tag name is specified, there will be fewer elements to // filter through when going by class than by tag name if (opt_class && parent.getElementsByClassName) { var els = parent.getElementsByClassName(opt_class); if (tagName) { var arrayLike = {}; var len = 0; // Filter for specific tags if requested. for (var i = 0, el; el = els[i]; i++) { if (tagName == el.nodeName.toLowerCase()) { arrayLike[len++] = el; } } arrayLike.length = len; return arrayLike; } else { return els; } } var els = parent.getElementsByTagName(tagName || '*'); if (opt_class) { var arrayLike = {}; var len = 0; for (var i = 0, el; el = els[i]; i++) { var className = el.className; // Check if className has a split function since SVG className does not. if (typeof className.split == 'function' && goog.array.contains(className.split(' '), opt_class)) { arrayLike[len++] = el; } } arrayLike.length = len; return arrayLike; } else { return els; } }; /** * Alias for {@code getElementsByTagNameAndClass}. * @param {?string} opt_tag Element tag name. * @param {?string} opt_class Optional class name. * @param {Element} opt_el Optional element to look in. * @return { {length: number} } Array-like list of elements (only a length * property and numerical indices are guaranteed to exist). */ goog.dom.$$ = goog.dom.getElementsByTagNameAndClass; /** * Sets multiple properties on a node. * @param {Element} element DOM node to set properties on. * @param {Object} properties Hash of property:value pairs. */ goog.dom.setProperties = function(element, properties) { goog.object.forEach(properties, function(val, key) { if (key == 'style') { element.style.cssText = val; } else if (key == 'class') { element.className = val; } else if (key == 'for') { element.htmlFor = val; } else if (key in goog.dom.DIRECT_ATTRIBUTE_MAP_) { element.setAttribute(goog.dom.DIRECT_ATTRIBUTE_MAP_[key], val); } else { element[key] = val; } }); }; /** * Map of attributes that should be set using * element.setAttribute(key, val) instead of element[key] = val. Used * by goog.dom.setProperties. * * @type {Object} * @private */ goog.dom.DIRECT_ATTRIBUTE_MAP_ = { 'cellpadding': 'cellPadding', 'cellspacing': 'cellSpacing', 'colspan': 'colSpan', 'rowspan': 'rowSpan', 'valign': 'vAlign', 'height': 'height', 'width': 'width', 'usemap': 'useMap', 'frameborder': 'frameBorder', 'type': 'type' }; /** * Gets the dimensions of the viewport. * * Gecko Standards mode: * docEl.clientWidth Width of viewport excluding scrollbar. * win.innerWidth Width of viewport including scrollbar. * body.clientWidth Width of body element. * * docEl.clientHeight Height of viewport excluding scrollbar. * win.innerHeight Height of viewport including scrollbar. * body.clientHeight Height of document. * * Gecko Backwards compatible mode: * docEl.clientWidth Width of viewport excluding scrollbar. * win.innerWidth Width of viewport including scrollbar. * body.clientWidth Width of viewport excluding scrollbar. * * docEl.clientHeight Height of document. * win.innerHeight Height of viewport including scrollbar. * body.clientHeight Height of viewport excluding scrollbar. * * IE6/7 Standards mode: * docEl.clientWidth Width of viewport excluding scrollbar. * win.innerWidth Undefined. * body.clientWidth Width of body element. * * docEl.clientHeight Height of viewport excluding scrollbar. * win.innerHeight Undefined. * body.clientHeight Height of document element. * * IE5 + IE6/7 Backwards compatible mode: * docEl.clientWidth 0. * win.innerWidth Undefined. * body.clientWidth Width of viewport excluding scrollbar. * * docEl.clientHeight 0. * win.innerHeight Undefined. * body.clientHeight Height of viewport excluding scrollbar. * * Opera 9 Standards and backwards compatible mode: * docEl.clientWidth Width of viewport excluding scrollbar. * win.innerWidth Width of viewport including scrollbar. * body.clientWidth Width of viewport excluding scrollbar. * * docEl.clientHeight Height of document. * win.innerHeight Height of viewport including scrollbar. * body.clientHeight Height of viewport excluding scrollbar. * * WebKit: * Safari 2 * docEl.clientHeight Same as scrollHeight. * docEl.clientWidth Same as innerWidth. * win.innerWidth Width of viewport excluding scrollbar. * win.innerHeight Height of the viewport including scrollbar. * frame.innerHeight Height of the viewport exluding scrollbar. * * Safari 3 (tested in 522) * * docEl.clientWidth Width of viewport excluding scrollbar. * docEl.clientHeight Height of viewport excluding scrollbar in strict mode. * body.clientHeight Height of viewport excluding scrollbar in quirks mode. * * @param {Window} opt_window Optional window element to test. * @return {!goog.math.Size} Object with values 'width' and 'height'. */ goog.dom.getViewportSize = function(opt_window) { // TODO: This should not take an argument return goog.dom.getViewportSize_(opt_window || window); }; /** * Helper for {@code getViewportSize}. * @param {Window} win The window to get the view port size for. * @return {!goog.math.Size} Object with values 'width' and 'height'. * @private */ goog.dom.getViewportSize_ = function(win) { var doc = win.document; if (goog.userAgent.WEBKIT && !goog.userAgent.isVersion('500') && !goog.userAgent.MOBILE) { // TODO: Sometimes we get something that isn't a valid window // object. In this case we just revert to the current window. We need to // figure out when this happens and find a real fix for it. // See the comments on goog.dom.getWindow. if (typeof win.innerHeight == 'undefined') { win = window; } var innerHeight = win.innerHeight; var scrollHeight = win.document.documentElement.scrollHeight; if (win == win.top) { if (scrollHeight < innerHeight) { innerHeight -= 15; // Scrollbars are 15px wide on Mac } } return new goog.math.Size(win.innerWidth, innerHeight); } var el = goog.dom.isCss1CompatMode_(doc) && // Older versions of Opera used to read from document.body, but this // changed with 9.5 (!goog.userAgent.OPERA || goog.userAgent.OPERA && goog.userAgent.isVersion('9.50')) ? doc.documentElement : doc.body; return new goog.math.Size(el.clientWidth, el.clientHeight); }; /** * Calculates the height of the document. * * @return {number} The height of the current document. */ goog.dom.getDocumentHeight = function() { return goog.dom.getDocumentHeight_(window); }; /** * Calculates the height of the document of the given window. * * Function code copied from the opensocial gadget api: * gadgets.window.adjustHeight(opt_height) * * @private * @param {Window} win The window whose document height to retrieve. * @return {number} The height of the document of the given window. */ goog.dom.getDocumentHeight_ = function(win) { // NOTE: This method will return the window size rather than the document // size in webkit quirks mode. var doc = win.document; var height = 0; if (doc) { // Calculating inner content height is hard and different between // browsers rendering in Strict vs. Quirks mode. We use a combination of // three properties within document.body and document.documentElement: // - scrollHeight // - offsetHeight // - clientHeight // These values differ significantly between browsers and rendering modes. // But there are patterns. It just takes a lot of time and persistence // to figure out. // Get the height of the viewport var vh = goog.dom.getViewportSize_(win).height; var body = doc.body; var docEl = doc.documentElement; if (goog.dom.isCss1CompatMode_(doc) && docEl.scrollHeight) { // In Strict mode: // The inner content height is contained in either: // document.documentElement.scrollHeight // document.documentElement.offsetHeight // Based on studying the values output by different browsers, // use the value that's NOT equal to the viewport height found above. height = docEl.scrollHeight != vh ? docEl.scrollHeight : docEl.offsetHeight; } else { // In Quirks mode: // documentElement.clientHeight is equal to documentElement.offsetHeight // except in IE. In most browsers, document.documentElement can be used // to calculate the inner content height. // However, in other browsers (e.g. IE), document.body must be used // instead. How do we know which one to use? // If document.documentElement.clientHeight does NOT equal // document.documentElement.offsetHeight, then use document.body. var sh = docEl.scrollHeight; var oh = docEl.offsetHeight; if (docEl.clientHeight != oh) { sh = body.scrollHeight; oh = body.offsetHeight; } // Detect whether the inner content height is bigger or smaller // than the bounding box (viewport). If bigger, take the larger // value. If smaller, take the smaller value. if (sh > vh) { // Content is larger height = sh > oh ? sh : oh; } else { // Content is smaller height = sh < oh ? sh : oh; } } } return height; }; /** * Gets the page scroll distance as a coordinate object. * * @param {Window} opt_window Optional window element to test. * @return {!goog.math.Coordinate} Object with values 'x' and 'y'. * @deprecated Use {@link goog.dom.getDocumentScroll} instead. */ goog.dom.getPageScroll = function(opt_window) { var win = opt_window || goog.global || window; return goog.dom.getDomHelper(win.document).getDocumentScroll(); }; /** * Gets the document scroll distance as a coordinate object. * * @return {!goog.math.Coordinate} Object with values 'x' and 'y'. */ goog.dom.getDocumentScroll = function() { return goog.dom.getDocumentScroll_(document); }; /** * Helper for {@code getDocumentScroll}. * * @param {!Document} doc The document to get the scroll for. * @return {!goog.math.Coordinate} Object with values 'x' and 'y'. * @private */ goog.dom.getDocumentScroll_ = function(doc) { var el = goog.dom.getDocumentScrollElement_(doc); return new goog.math.Coordinate(el.scrollLeft, el.scrollTop); }; /** * Gets the document scroll element. * @return {Element} Scrolling element. */ goog.dom.getDocumentScrollElement = function() { return goog.dom.getDocumentScrollElement_(document); }; /** * Helper for {@code getDocumentScrollElement}. * @param {!Document} doc The document to get the scroll element for. * @return {Element} Scrolling element. * @private */ goog.dom.getDocumentScrollElement_ = function(doc) { // Safari (2 and 3) needs body.scrollLeft in both quirks mode and strict mode. return !goog.userAgent.WEBKIT && goog.dom.isCss1CompatMode_(doc) ? doc.documentElement : doc.body; }; /** * Gets the window object associated with the given document. * * @param {Document} opt_doc Document object to get window for. * @return {Window} The window associated with the given document. */ goog.dom.getWindow = function(opt_doc) { // TODO: This should not take an argument. return opt_doc ? goog.dom.getWindow_(opt_doc) : window; }; /** * Helper for {@code getWindow}. * * @param {!Document} doc Document object to get window for. * @return {!Window} The window associated with the given document. * @private */ goog.dom.getWindow_ = function(doc) { if (doc.parentWindow) { return doc.parentWindow; } if (goog.userAgent.WEBKIT && !goog.userAgent.isVersion('500') && !goog.userAgent.MOBILE) { // NOTE: document.defaultView is a valid object under Safari 2, but // it's not a window object, it's an AbstractView object. You can use it to // get computed CSS style, but it doesn't have the full functionality of a // DOM window. So for Safari 2 we use the following hack: var scriptElement = doc.createElement('script'); scriptElement.innerHTML = 'document.parentWindow=window'; var parentElement = doc.documentElement; parentElement.appendChild(scriptElement); parentElement.removeChild(scriptElement); return doc.parentWindow; } return doc.defaultView; }; /** * Returns a dom node with a set of attributes. This function accepts varargs * for subsequent nodes to be added. Subsequent nodes will be added to the * first node as childNodes. * * So: * <code>createDom('div', null, createDom('p'), createDom('p'));</code> * would return a div with two child paragraphs * * @param {string} tagName Tag to create. * @param {Object|string} opt_attributes If object, then a map of name-value * pairs for attributes. If a string, then this is the className of the new * element. * @param {Object|string|Array|NodeList} var_args Further DOM nodes or strings * for text nodes. If one of the var_args is an array or NodeList, its * elements will be added as childNodes instead. * @return {!Element} Reference to a DOM node. */ goog.dom.createDom = function(tagName, opt_attributes, var_args) { return goog.dom.createDom_(document, arguments); }; /** * Helper for {@code createDom}. * @param {!Document} doc The document to create the DOM in. * @param {Arguments} args Argument object passed from the callers. See * {@code goog.dom.createDom} for details. * @return {!Element} Reference to a DOM node. * @private */ goog.dom.createDom_ = function(doc, args) { var tagName = args[0]; var attributes = args[1]; // Internet Explorer is dumb: http://msdn.microsoft.com/workshop/author/ // dhtml/reference/properties/name_2.asp // Also does not allow setting of 'type' attribute on 'input' or 'button'. if (goog.userAgent.IE && attributes && (attributes.name || attributes.type)) { var tagNameArr = ['<', tagName]; if (attributes.name) { tagNameArr.push(' name="', goog.string.htmlEscape(attributes.name), '"'); } if (attributes.type) { tagNameArr.push(' type="', goog.string.htmlEscape(attributes.type), '"'); // Create copy of attribute map to remove 'type' without mutating argument attributes = goog.cloneObject(attributes); delete attributes.type; } tagNameArr.push('>'); tagName = tagNameArr.join(''); } var element = doc.createElement(tagName); if (attributes) { if (goog.isString(attributes)) { element.className = attributes; } else { goog.dom.setProperties(element, attributes); } } if (args.length > 2) { function childHandler(child) { // TODO: More coercion, ala MochiKit? if (child) { element.appendChild(goog.isString(child) ? doc.createTextNode(child) : child); } } for (var i = 2; i < args.length; i++) { var arg = args[i]; // TODO: Fix isArrayLike to return false for a text node. if (goog.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) { // If the argument is a node list, not a real array, use a clone, // because forEach can't be used to mutate a NodeList. goog.array.forEach(goog.dom.isNodeList(arg) ? goog.array.clone(arg) : arg, childHandler); } else { childHandler(arg); } } } return element; }; /** * Alias for {@code createDom}. * @param {string} tagName Tag to create. * @param {string|Object} opt_attributes If object, then a map of name-value * pairs for attributes. If a string, then this is the className of the new * element. * @param {Object|Array} var_args Further DOM nodes or strings for text nodes. * If one of the var_args is an array, its children will be added as * childNodes instead. * @return {!Element} Reference to a DOM node. */ goog.dom.$dom = goog.dom.createDom; /** * Creates a new element. * @param {string} name Tag name. * @return {!Element} The new element. */ goog.dom.createElement = function(name) { return document.createElement(name); }; /** * Creates a new text node. * @param {string} content Content. * @return {!Text} The new text node. */ goog.dom.createTextNode = function(content) { return document.createTextNode(content); }; /** * Converts an HTML string into a document fragment. * * @param {string} htmlString The HTML string to convert. * @return {!Node} The resulting document fragment. */ goog.dom.htmlToDocumentFragment = function(htmlString) { return goog.dom.htmlToDocumentFragment_(document, htmlString); }; /** * Helper for {@code htmlToDocumentFragment}. * * @param {!Document} doc The document. * @param {string} htmlString The HTML string to convert. * @return {!Node} The resulting document fragment. * @private */ goog.dom.htmlToDocumentFragment_ = function(doc, htmlString) { var tempDiv = doc.createElement('div'); tempDiv.innerHTML = htmlString; if (tempDiv.childNodes.length == 1) { return /** @type {!Node} */ (tempDiv.firstChild); } else { var fragment = doc.createDocumentFragment(); while (tempDiv.firstChild) { fragment.appendChild(tempDiv.firstChild); } return fragment; } }; /** * Returns the compatMode of the document. * @return {string} The result is either CSS1Compat or BackCompat. * @deprecated use goog.dom.isCss1CompatMode instead. */ goog.dom.getCompatMode = function() { return goog.dom.isCss1CompatMode() ? 'CSS1Compat' : 'BackCompat'; }; /** * Returns true if the browser is in "CSS1-compatible" (standards-compliant) * mode, false otherwise. * @return {boolean} True if in CSS1-compatible mode. */ goog.dom.isCss1CompatMode = function() { return goog.dom.isCss1CompatMode_(document); }; /** * Returns true if the browser is in "CSS1-compatible" (standards-compliant) * mode, false otherwise. * @param {Document} doc The document to check. * @return {boolean} True if in CSS1-compatible mode. * @private */ goog.dom.isCss1CompatMode_ = function(doc) { if (goog.dom.COMPAT_MODE_KNOWN_) { return goog.dom.ASSUME_STANDARDS_MODE; } return doc.compatMode == 'CSS1Compat'; }; /** * Determines if the given node can contain children. * @param {Node} node The node to check. * @return {boolean} Whether the node can contain children. */ goog.dom.canHaveChildren = function(node) { if (node.nodeType != goog.dom.NodeType.ELEMENT) { return false; } if ('canHaveChildren' in node) { // IE supports this natively. return node.canHaveChildren; } switch (node.tagName) { case goog.dom.TagName.APPLET: case goog.dom.TagName.AREA: case goog.dom.TagName.BR: case goog.dom.TagName.COL: case goog.dom.TagName.FRAME: case goog.dom.TagName.HR: case goog.dom.TagName.IMG: case goog.dom.TagName.INPUT: case goog.dom.TagName.IFRAME: case goog.dom.TagName.ISINDEX: case goog.dom.TagName.LINK: case goog.dom.TagName.NOFRAMES: case goog.dom.TagName.NOSCRIPT: case goog.dom.TagName.META: case goog.dom.TagName.OBJECT: case goog.dom.TagName.PARAM: case goog.dom.TagName.SCRIPT: case goog.dom.TagName.STYLE: return false; } return true; }; /** * Appends a child to a node. * @param {Node} parent Parent. * @param {Node} child Child. */ goog.dom.appendChild = function(parent, child) { parent.appendChild(child); }; /** * Removes all the child nodes on a DOM node. * @param {Node} node Node to remove children from. */ goog.dom.removeChildren = function(node) { // Note: Iterations over live collections can be slow, this is the fastest // we could find. The double parenthesis are used to prevent JsCompiler and // strict warnings. var child; while ((child = node.firstChild)) { node.removeChild(child); } }; /** * Inserts a new node before an existing reference node (i.e. as the previous * sibling). If the reference node has no parent, then does nothing. * @param {Node} newNode Node to insert. * @param {Node} refNode Reference node to insert before. */ goog.dom.insertSiblingBefore = function(newNode, refNode) { if (refNode.parentNode) { refNode.parentNode.insertBefore(newNode, refNode); } }; /** * Inserts a new node after an existing reference node (i.e. as the next * sibling). If the reference node has no parent, then does nothing. * @param {Node} newNode Node to insert. * @param {Node} refNode Reference node to insert after. */ goog.dom.insertSiblingAfter = function(newNode, refNode) { if (refNode.parentNode) { refNode.parentNode.insertBefore(newNode, refNode.nextSibling); } }; /** * Removes a node from its parent. * @param {Node} node The node to remove. * @return {Node?} The node removed if removed; else, null. */ goog.dom.removeNode = function(node) { return node && node.parentNode ? node.parentNode.removeChild(node) : null; }; /** * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no * parent. * @param {Node} newNode Node to insert. * @param {Node} oldNode Node to replace. */ goog.dom.replaceNode = function(newNode, oldNode) { var parent = oldNode.parentNode; if (parent) { parent.replaceChild(newNode, oldNode); } }; /** * Flattens an element. That is, removes it and replace it with its children. * Does nothing if the element is not in the document. * @param {Element} element The element to flatten. * @return {Element|undefined} The original element, detached from the document * tree, sans children; or undefined, if the element was not in the * document to begin with. */ goog.dom.flattenElement = function(element) { var child, parent = element.parentNode; if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) { // Use IE DOM method (supported by Opera too) if available if (element.removeNode) { return /** @type {Element} */ (element.removeNode(false)); } else { // Move all children of the original node up one level. while ((child = element.firstChild)) { parent.insertBefore(child, element); } // Detach the original element. return /** @type {Element} */ (goog.dom.removeNode(element)); } } }; /** * Returns the first child node that is an element. * @param {Node} node The node to get the first child element of. * @return {Element?} The first child node of {@code node} that is an element. */ goog.dom.getFirstElementChild = function(node) { return goog.dom.getNextElementNode_(node.firstChild, true); }; /** * Returns the last child node that is an element. * @param {Node} node The node to get the last child element of. * @return {Element?} The last child node of {@code node} that is an element. */ goog.dom.getLastElementChild = function(node) { return goog.dom.getNextElementNode_(node.lastChild, false); }; /** * Returns the first next sibling that is an element. * @param {Node} node The node to get the next sibling element of. * @return {Element?} The next sibling of {@code node} that is an element. */ goog.dom.getNextElementSibling = function(node) { return goog.dom.getNextElementNode_(node.nextSibling, true); }; /** * Returns the first previous sibling that is an element. * @param {Node} node The node to get the previous sibling element of. * @return {Element?} The first previous sibling of {@code node} that is * an element. */ goog.dom.getPreviousElementSibling = function(node) { return goog.dom.getNextElementNode_(node.previousSibling, false); }; /** * Returns the first node that is an element in the specified direction, * starting with {@code node}. * @param {Node?} node The node to get the next element from. * @param {boolean} forward Whether to look forwards or backwards. * @return {Element?} The first element. * @private */ goog.dom.getNextElementNode_ = function(node, forward) { while (node && node.nodeType != goog.dom.NodeType.ELEMENT) { node = forward ? node.nextSibling : node.previousSibling; } return /** @type {Element?} */ (node); }; /** * Whether the object looks like a DOM node. * @param {Object} obj The object being tested for node likeness. * @return {boolean} Whether the object looks like a DOM node. */ goog.dom.isNodeLike = function(obj) { return goog.isObject(obj) && obj.nodeType > 0; }; /** * Safari contains is broken, but appears to be fixed in WebKit 522+ * @type {boolean} * @private */ goog.dom.BAD_CONTAINS_WEBKIT_ = goog.userAgent.WEBKIT && goog.userAgent.isVersion('522'); /** * Whether a node contains another node. * @param {Node} parent The node that should contain the other node. * @param {Node} descendant The node to test presence of. * @return {boolean} Whether the parent node contains the descendent node. */ goog.dom.contains = function(parent, descendant) { // We use browser specific methods for this if available since it is faster // that way. // IE / Safari(some) DOM if (typeof parent.contains != 'undefined' && !goog.dom.BAD_CONTAINS_WEBKIT_ && descendant.nodeType == goog.dom.NodeType.ELEMENT) { return parent == descendant || parent.contains(descendant); } // W3C DOM Level 3 if (typeof parent.compareDocumentPosition != 'undefined') { return parent == descendant || Boolean(parent.compareDocumentPosition(descendant) & 16); } // W3C DOM Level 1 while (descendant && parent != descendant) { descendant = descendant.parentNode; } return descendant == parent; }; /** * Compares the document order of two nodes, returning 0 if they are the same * node, a negative number if node1 is before node2, and a positive number if * node2 is before node1. Note that we compare the order the tags appear in the * document so in the tree <b><i>text</i></b> the B node is considered to be * before the I node. * * @param {Node} node1 The first node to compare. * @param {Node} node2 The second node to compare. * @return {number} 0 if the nodes are the same node, a negative number if node1 * is before node2, and a positive number if node2 is before node1. */ goog.dom.compareNodeOrder = function(node1, node2) { // Fall out quickly for equality. if (node1 == node2) { return 0; } // Use compareDocumentPosition where available if (node1.compareDocumentPosition) { // 4 is the bitmask for FOLLOWS. return node1.compareDocumentPosition(node2) & 2 ? 1 : -1; } // Process in IE using sourceIndex - we check to see if the first node has // a source index or if it's parent has one. if ('sourceIndex' in node1 || (node1.parentNode && 'sourceIndex' in node1.parentNode)) { var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT; var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT; if (isElement1 && isElement2) { return node1.sourceIndex - node2.sourceIndex; } else { var parent1 = node1.parentNode; var parent2 = node2.parentNode; if (parent1 == parent2) { return goog.dom.compareSiblingOrder_(node1, node2); } if (!isElement1 && goog.dom.contains(parent1, node2)) { return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2); } if (!isElement2 && goog.dom.contains(parent2, node1)) { return goog.dom.compareParentsDescendantNodeIe_(node2, node1); } return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) - (isElement2 ? node2.sourceIndex : parent2.sourceIndex); } } // For Safari, we compare ranges. var doc = goog.dom.getOwnerDocument(node1); var range1, range2; range1 = doc.createRange(); range1.selectNode(node1); range1.collapse(true); range2 = doc.createRange(); range2.selectNode(node2); range2.collapse(true); return range1.compareBoundaryPoints(goog.global['Range'].START_TO_END, range2); }; /** * Utility function to compare the position of two nodes, when * {@code textNode}'s parent is an ancestor of {@code node}. If this entry * condition is not met, this function will attempt to reference a null object. * @param {Node} textNode The textNode to compare. * @param {Node} node The node to compare. * @return {number} -1 if node is before textNode, +1 otherwise. * @private */ goog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) { var parent = textNode.parentNode; if (parent == node) { // If textNode is a child of node, then node comes first. return -1; } var sibling = node; while (sibling.parentNode != parent) { sibling = sibling.parentNode; } return goog.dom.compareSiblingOrder_(sibling, textNode); }; /** * Utility function to compare the position of two nodes known to be non-equal * siblings. * @param {Node} node1 The first node to compare. * @param {Node} node2 The second node to compare. * @return {number} -1 if node1 is before node2, +1 otherwise. * @private */ goog.dom.compareSiblingOrder_ = function(node1, node2) { var s = node2; while ((s = s.previousSibling)) { if (s == node1) { // We just found node1 before node2. return -1; } } // Since we didn't find it, node1 must be after node2. return 1; }; /** * Find the deepest common ancestor of the given nodes. * @param {Node} var_args The nodes to find a common ancestor of. * @return {Node?} The common ancestor of the nodes, or null if there is none. * null will only be returned if two or more of the nodes are from different * documents. */ goog.dom.findCommonAncestor = function(var_args) { var i, count = arguments.length; if (!count) { return null; } else if (count == 1) { return arguments[0]; } var paths = []; var minLength = Infinity; for (i = 0; i < count; i++) { // Compute the list of ancestors. var ancestors = []; var node = arguments[i]; while (node) { ancestors.unshift(node); node = node.parentNode; } // Save the list for comparison. paths.push(ancestors); minLength = Math.min(minLength, ancestors.length); } var output = null; for (i = 0; i < minLength; i++) { var first = paths[0][i]; for (var j = 1; j < count; j++) { if (first != paths[j][i]) { return output; } } output = first; } return output; }; /** * Returns the owner document for a node. * @param {Node|Window} node The node to get the document for. * @return {!Document} The document owning the node. */ goog.dom.getOwnerDocument = function(node) { // TODO: Remove IE5 code. // IE5 uses document instead of ownerDocument return /** @type {!Document} */ ( node.nodeType == goog.dom.NodeType.DOCUMENT ? node : node.ownerDocument || node.document); }; /** * Cross-browser function for getting the document element of a frame or iframe. * @param {Element} frame Frame element. * @return {!Document} The frame content document. */ goog.dom.getFrameContentDocument = function(frame) { var doc; if (goog.userAgent.WEBKIT) { doc = (frame.document || frame.contentWindow.document); } else { doc = (frame.contentDocument || frame.contentWindow.document); } return doc; }; /** * Cross-browser function for getting the window of a frame or iframe. * @param {HTMLIFrameElement|HTMLFrameElement} frame Frame element. * @return {Window} The window associated with the given frame. */ goog.dom.getFrameContentWindow = function(frame) { return frame.contentWindow || goog.dom.getWindow_(goog.dom.getFrameContentDocument(frame)); }; /** * Cross-browser function for setting the text content of an element. * @param {Element} element The element to change the text content of. * @param {string} text The string that should replace the current element * content. */ goog.dom.setTextContent = function(element, text) { if ('textContent' in element) { element.textContent = text; } else if (element.firstChild && element.firstChild.nodeType == goog.dom.NodeType.TEXT) { // If the first child is a text node we just change its data and remove the // rest of the children. while (element.lastChild != element.firstChild) { element.removeChild(element.lastChild); } element.firstChild.data = text; } else { goog.dom.removeChildren(element); var doc = goog.dom.getOwnerDocument(element); element.appendChild(doc.createTextNode(text)); } }; /** * Gets the outerHTML of a node, which islike innerHTML, except that it * actually contains the HTML of the node itself. * @param {Element} element The element to get the HTML of. * @return {string} The outerHTML of the given element. */ goog.dom.getOuterHtml = function(element) { // IE, Opera and WebKit all have outerHTML. if ('outerHTML' in element) { return element.outerHTML; } else { var doc = goog.dom.getOwnerDocument(element); var div = doc.createElement('div'); div.appendChild(element.cloneNode(true)); return div.innerHTML; } }; /** * Finds the first descendant node that matches the filter function, using * a depth first search. This function offers the most general purpose way * of finding a matching element. You may also wish to consider * {@code goog.dom.query} which can express many matching criteria using * CSS selector expressions. These expressions often result in a more * compact representation of the desired result. * @see goog.dom.query * * @param {Node} root The root of the tree to search. * @param {function(Node) : boolean} p The filter function. * @return {Node|undefined} The found node or undefined if none is found. */ goog.dom.findNode = function(root, p) { var rv = []; var found = goog.dom.findNodes_(root, p, rv, true); return found ? rv[0] : undefined; }; /** * Finds all the descendant nodes that match the filter function, using a * a depth first search. This function offers the most general-purpose way * of finding a set of matching elements. You may also wish to consider * {@code goog.dom.query} which can express many matching criteria using * CSS selector expressions. These expressions often result in a more * compact representation of the desired result. * @param {Node} root The root of the tree to search. * @param {function(Node) : boolean} p The filter function. * @return {Array.<Node>} The found nodes or an empty array if none are found. */ goog.dom.findNodes = function(root, p) { var rv = []; goog.dom.findNodes_(root, p, rv, false); return rv; }; /** * Finds the first or all the descendant nodes that match the filter function, * using a depth first search. * @param {Node?} root The root of the tree to search. * @param {function(Node) : boolean} p The filter function. * @param {Array.<Node>} rv The found nodes are added to this array. * @param {boolean} findOne If true we exit after the first found node. * @return {boolean} Whether the search is complete or not. True in case findOne * is true and the node is found. False otherwise. * @private */ goog.dom.findNodes_ = function(root, p, rv, findOne) { if (root != null) { for (var i = 0, child; child = root.childNodes[i]; i++) { if (p(child)) { rv.push(child); if (findOne) { return true; } } if (goog.dom.findNodes_(child, p, rv, findOne)) { return true; } } } return false; }; /** * Map of tags whose content to ignore when calculating text length. * @type {Object} * @private */ goog.dom.TAGS_TO_IGNORE_ = { 'SCRIPT': 1, 'STYLE': 1, 'HEAD': 1, 'IFRAME': 1, 'OBJECT': 1 }; /** * Map of tags which have predefined values with regard to whitespace. * @type {Object} * @private */ goog.dom.PREDEFINED_TAG_VALUES_ = {'IMG': ' ', 'BR': '\n'}; /** * Returns true if the element has a tab index that allows it to receive * keyboard focus (tabIndex >= 0), false otherwise. Note that form elements * natively support keyboard focus, even if they have no tab index. See * http://go/tabindex for more info. * @param {Element} element Element to check. * @return {boolean} Whether the element has a tab index that allows keyboard * focus. */ goog.dom.isFocusableTabIndex = function(element) { // IE returns 0 for an unset tabIndex, so we must use getAttributeNode(), // which returns an object with a 'specified' property if tabIndex is // specified. This works on other browsers, too. var attrNode = element.getAttributeNode('tabindex'); // Must be lowercase! if (attrNode && attrNode.specified) { var index = element.tabIndex; return goog.isNumber(index) && index >= 0; } return false; }; /** * Enables or disables keyboard focus support on the element via its tab index. * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true * (or elements that natively support keyboard focus, like form elements) can * receive keyboard focus. See http://go/tabindex for more info. * @param {Element} element Element whose tab index is to be changed. * @param {boolean} enable Whether to set or remove a tab index on the element * that supports keyboard focus. */ goog.dom.setFocusableTabIndex = function(element, enable) { if (enable) { element.tabIndex = 0; } else { element.removeAttribute('tabIndex'); // Must be camelCase! } }; /** * Returns the text content of the current node, without markup and invisible * symbols. New lines are stripped and whitespace is collapsed, * such that each character would be visible. * * In browsers that support it, innerText is used. Other browsers attempt to * simulate it via node traversal. Line breaks are canonicalized in IE. * * @param {Node} node The node from which we are getting content. * @return {string} The text content. */ goog.dom.getTextContent = function(node) { var textContent; // NOTE: Both Opera and Safara 3 supports innerText but they include // text nodes in script tags. So we revert to use a user agent test here. if (goog.userAgent.IE && ('innerText' in node)) { textContent = goog.string.canonicalizeNewlines(node.innerText); // Unfortunately .innerText() returns text with ­ symbols // We need to filter it out and then remove duplicate whitespaces } else { var buf = []; goog.dom.getTextContent_(node, buf, true); textContent = buf.join(''); } // Strip ­ entities. goog.format.insertWordBreaks inserts them in Opera. textContent = textContent.replace(/\xAD/g, ''); textContent = textContent.replace(/ +/g, ' '); if (textContent != ' ') { textContent = textContent.replace(/^\s*/, ''); } return textContent; }; /** * Returns the text content of the current node, without markup. * * Unlike {@code getTextContent} this method does not collapse whitespaces * or normalize lines breaks. * * @param {Node} node The node from which we are getting content. * @return {string} The raw text content. */ goog.dom.getRawTextContent = function(node) { var buf = []; goog.dom.getTextContent_(node, buf, false); return buf.join(''); }; /** * Recursive support function for text content retrieval. * * @param {Node} node The node from which we are getting content. * @param {Array} buf string buffer. * @param {boolean} normalizeWhitespace Whether to normalize whitespace. * @private */ goog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) { if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) { // ignore certain tags } else if (node.nodeType == goog.dom.NodeType.TEXT) { if (normalizeWhitespace) { buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, '')); } else { buf.push(node.nodeValue); } } else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) { buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]); } else { var child = node.firstChild; while (child) { goog.dom.getTextContent_(child, buf, normalizeWhitespace); child = child.nextSibling; } } }; /** * Returns the text length of the text contained in a node, without markup. This * is equivalent to the selection length if the node was selected, or the number * of cursor movements to traverse the node. Images & BRs take one space. New * lines are ignored. * * @param {Node} node The node whose text content length is being calculated. * @return {number} The length of {@code node}'s text content. */ goog.dom.getNodeTextLength = function(node) { return goog.dom.getTextContent(node).length; }; /** * Returns the text offset of a node relative to one of its ancestors. The text * length is the same as the length calculated by goog.dom.getNodeTextLength. * * @param {Node} node The node whose offset is being calculated. * @param {Node} opt_offsetParent The node relative to which the offset will * be calculated. Defaults to the node's owner document's body. * @return {number} The text offset. */ goog.dom.getNodeTextOffset = function(node, opt_offsetParent) { var root = opt_offsetParent || goog.dom.getOwnerDocument(node).body; var buf = []; while (node && node != root) { var cur = node; while ((cur = cur.previousSibling)) { buf.unshift(goog.dom.getTextContent(cur)); } node = node.parentNode; } // Trim left to deal with FF cases when there might be line breaks and empty // nodes at the front of the text return goog.string.trimLeft(buf.join('')).replace(/ +/g, ' ').length; }; /** * Returns the node at a given offset in a parent node. If an object is * provided for the optional third parameter, the node and the remainder of the * offset will stored as properties of this object. * @param {Node} parent The parent node. * @param {number} offset The offset into the parent node. * @param {Object} opt_result Object to be used to store the return value. The * return value will be stored in the form {node: Node, remainder: number} * if this object is provided. * @return {Node} The node at the given offset. */ goog.dom.getNodeAtOffset = function(parent, offset, opt_result) { var stack = [parent], pos = 0, cur; while (stack.length > 0 && pos < offset) { cur = stack.pop(); if (cur.nodeName in goog.dom.TAGS_TO_IGNORE_) { // ignore certain tags } else if (cur.nodeType == goog.dom.NodeType.TEXT) { var text = cur.nodeValue.replace(/(\r\n|\r|\n)/g, '').replace(/ +/g, ' '); pos += text.length; } else if (cur.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) { pos += goog.dom.PREDEFINED_TAG_VALUES_[cur.nodeName].length; } else { for (var i = cur.childNodes.length - 1; i >= 0; i--) { stack.push(cur.childNodes[i]); } } } if (goog.isObject(opt_result)) { opt_result.remainder = cur ? cur.nodeValue.length + offset - pos - 1 : 0; opt_result.node = cur; } return cur; }; /** * Returns true if the object is a {@code NodeList}. To qualify as a NodeList, * the object must have a numeric length property and an item function (which * has type 'string' on IE for some reason). * @param {Object?} val Object to test. * @return {boolean} Whether the object is a NodeList. */ goog.dom.isNodeList = function(val) { // TODO: Now the isNodeList is part of goog.dom we can use // goog.userAgent to make this simpler. // A NodeList must have a length property of type 'number' on all platforms. if (val && typeof val.length == 'number') { // A NodeList is an object everywhere except Safari, where it's a function. if (goog.isObject(val)) { // A NodeList must have an item function (on non-IE platforms) or an item // property of type 'string' (on IE). return typeof val.item == 'function' || typeof val.item == 'string'; } else if (goog.isFunction(val)) { // On Safari, a NodeList is a function with an item property that is also // a function. return typeof val.item == 'function'; } } // Not a NodeList. return false; }; /** * Walks up the DOM hierarchy returning the first ancestor that has the passed * tag name and/or class name. If the passed element matches the specified * criteria, the element itself is returned. * @param {Node} element The DOM node to start with. * @param {?string} opt_tag The tag name to match (or null/undefined to match * any node regardless of tag name). Must be uppercase (goog.dom.TagName). * @param {?string} opt_class The class name to match (or null/undefined to * match any node regardless of class name). * @return {Node?} The first ancestor that matches the passed criteria, or * null if none match. */ goog.dom.getAncestorByTagNameAndClass = function(element, opt_tag, opt_class) { return goog.dom.getAncestor(element, function(node) { return (!opt_tag || node.nodeName == opt_tag) && (!opt_class || goog.dom.classes.has(node, opt_class)); }, true); }; /** * Walks up the DOM hierarchy returning the first ancestor that passes the * matcher function. * @param {Node} element The DOM node to start with. * @param {function(Node) : boolean} matcher A function that returns true if the * passed node matches the desired criteria. * @param {boolean} opt_includeNode If true, the node itself is included in * the search (the first call to the matcher will pass startElement as * the node to test). * @param {number} opt_maxSearchSteps Maximum number of levels to search up the * dom. * @return {Node?} DOM node that matched the matcher, or null if there was * no match. */ goog.dom.getAncestor = function( element, matcher, opt_includeNode, opt_maxSearchSteps) { if (!opt_includeNode) { element = element.parentNode; } var ignoreSearchSteps = opt_maxSearchSteps == null; var steps = 0; while (element && (ignoreSearchSteps || steps <= opt_maxSearchSteps)) { if (matcher(element)) { return element; } element = element.parentNode; steps++; } // Reached the root of the DOM without a match return null; }; /** * Create an instance of a DOM helper with a new document object. * @param {Document} opt_document Document object to associate with this * DOM helper. * @constructor */ goog.dom.DomHelper = function(opt_document) { /** * Reference to the document object to use * @type {!Document} * @private */ this.document_ = opt_document || goog.global.document || document; }; /** * Gets the dom helper object for the document where the element resides. * @param {Node} opt_node If present, gets the DomHelper for this node. * @return {!goog.dom.DomHelper} The DomHelper. */ goog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper; /** * Sets the document object. * @param {!Document} document Document object. */ goog.dom.DomHelper.prototype.setDocument = function(document) { this.document_ = document; }; /** * Gets the document object being used by the dom library. * @return {!Document} Document object. */ goog.dom.DomHelper.prototype.getDocument = function() { return this.document_; }; /** * Alias for {@code getElementById}. If a DOM node is passed in then we just * return that. * @param {string|Element} element Element ID or a DOM node. * @return {Element} The element with the given ID, or the node passed in. */ goog.dom.DomHelper.prototype.getElement = function(element) { if (goog.isString(element)) { return this.document_.getElementById(element); } else { return element; } }; /** * Alias for {@code getElement}. * @param {string|Element} element Element ID or a DOM node. * @return {Element} The element with the given ID, or the node passed in. */ goog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement; /** * Looks up elements by both tag and class name, using browser native functions * ({@code querySelectorAll}, {@code getElementsByTagName} or * {@code getElementsByClassName}) where possible. The returned array is a live * NodeList or a static list depending on the code path taken. * * @see goog.dom.query * * @param {?string} opt_tag Element tag name or * for all tags. * @param {?string} opt_class Optional class name. * @param {Element} opt_el Optional element to look in. * @return { {length: number} } Array-like list of elements (only a length * property and numerical indices are guaranteed to exist). */ goog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) { return goog.dom.getElementsByTagNameAndClass_(this.document_, opt_tag, opt_class, opt_el); }; /** * Alias for {@code getElementsByTagNameAndClass}. * @deprecated Use DomHelper getElementsByTagNameAndClass. * @see goog.dom.query * * @param {?string} opt_tag Element tag name. * @param {?string} opt_class Optional class name. * @param {Element} opt_el Optional element to look in. * @return { {length: number} } Array-like list of elements (only a length * property and numerical indices are guaranteed to exist). */ goog.dom.DomHelper.prototype.$$ = goog.dom.DomHelper.prototype.getElementsByTagNameAndClass; /** * Sets a number of properties on a node. * @param {Element} element DOM node to set properties on. * @param {Object} properties Hash of property:value pairs. */ goog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties; /** * Gets the dimensions of the viewport. * @param {Window} opt_window Optional window element to test. Defaults to * the window of the Dom Helper. * @return {!goog.math.Size} Object with values 'width' and 'height'. */ goog.dom.DomHelper.prototype.getViewportSize = function(opt_window) { // TODO: This should not take an argument. That breaks the rule of a // a DomHelper representing a single frame/window/document. return goog.dom.getViewportSize(opt_window || this.getWindow()); }; /** * Calculates the height of the document. * * @return {number} The height of the document. */ goog.dom.DomHelper.prototype.getDocumentHeight = function() { return goog.dom.getDocumentHeight_(this.getWindow()); }; /** * Returns a dom node with a set of attributes. This function accepts varargs * for subsequent nodes to be added. Subsequent nodes will be added to the * first node as childNodes. * * So: * <code>createDom('div', null, createDom('p'), createDom('p'));</code> * would return a div with two child paragraphs * * An easy way to move all child nodes of an existing element to a new parent * element is: * <code>createDom('div', null, oldElement.childNodes);</code> * which will remove all child nodes from the old element and add them as * child nodes of the new DIV. * * @param {string} tagName Tag to create. * @param {Object|string} opt_attributes If object, then a map of name-value * pairs for attributes. If a string, then this is the className of the new * element. * @param {Object|string|Array|NodeList} var_args Further DOM nodes or strings * for text nodes. If one of the var_args is an array or NodeList, its * elements will be added as childNodes instead. * @return {!Element} Reference to a DOM node. */ goog.dom.DomHelper.prototype.createDom = function(tagName, opt_attributes, var_args) { return goog.dom.createDom_(this.document_, arguments); }; /** * Alias for {@code createDom}. * @param {string} tagName Tag to create. * @param {Object|string} opt_attributes If object, then a map of name-value * pairs for attributes. If a string, then this is the className of the new * element. * @param {Object|Array} var_args Further DOM nodes or strings for text nodes. * If one of the var_args is an array, its children will be added as * childNodes instead. * @return {!Element} Reference to a DOM node. */ goog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom; /** * Creates a new element. * @param {string} name Tag name. * @return {!Element} The new element. */ goog.dom.DomHelper.prototype.createElement = function(name) { return this.document_.createElement(name); }; /** * Creates a new text node. * @param {string} content Content. * @return {!Text} The new text node. */ goog.dom.DomHelper.prototype.createTextNode = function(content) { return this.document_.createTextNode(content); }; /** * Converts an HTML string into a node or a document fragment. A single Node * is used if the {@code htmlString} only generates a single node. If the * {@code htmlString} generates multiple nodes then these are put inside a * {@code DocumentFragment}. * * @param {string} htmlString The HTML string to convert. * @return {!Node} The resulting node. */ goog.dom.DomHelper.prototype.htmlToDocumentFragment = function(htmlString) { return goog.dom.htmlToDocumentFragment_(this.document_, htmlString); }; /** * Returns the compatMode of the document. * @return {string} The result is either CSS1Compat or BackCompat. * @deprecated use goog.dom.DomHelper.prototype.isCss1CompatMode instead. */ goog.dom.DomHelper.prototype.getCompatMode = function() { return this.isCss1CompatMode() ? 'CSS1Compat' : 'BackCompat'; }; /** * Returns true if the browser is in "CSS1-compatible" (standards-compliant) * mode, false otherwise. * @return {boolean} True if in CSS1-compatible mode. */ goog.dom.DomHelper.prototype.isCss1CompatMode = function() { return goog.dom.isCss1CompatMode_(this.document_); }; /** * Gets the window object associated with the document. * @return {!Window} The window associated with the given document. */ goog.dom.DomHelper.prototype.getWindow = function() { return goog.dom.getWindow_(this.document_); }; /** * Gets the document scroll element. * @return {Element} Scrolling element. */ goog.dom.DomHelper.prototype.getDocumentScrollElement = function() { return goog.dom.getDocumentScrollElement_(this.document_); }; /** * Gets the document scroll distance as a coordinate object. * @return {!goog.math.Coordinate} Object with properties 'x' and 'y'. */ goog.dom.DomHelper.prototype.getDocumentScroll = function() { return goog.dom.getDocumentScroll_(this.document_); }; /** * Appends a child to a node. * @param {Node} parent Parent. * @param {Node} child Child. */ goog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild; /** * Removes all the child nodes on a DOM node. * @param {Node} node Node to remove children from. */ goog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren; /** * Inserts a new node before an existing reference node (i.e., as the previous * sibling). If the reference node has no parent, then does nothing. * @param {Node} newNode Node to insert. * @param {Node} refNode Reference node to insert before. */ goog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore; /** * Inserts a new node after an existing reference node (i.e., as the next * sibling). If the reference node has no parent, then does nothing. * @param {Node} newNode Node to insert. * @param {Node} refNode Reference node to insert after. */ goog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter; /** * Removes a node from its parent. * @param {Node} node The node to remove. * @return {Node?} The node removed if removed; else, null. */ goog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode; /** * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no * parent. * @param {Node} newNode Node to insert. * @param {Node} oldNode Node to replace. */ goog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode; /** * Flattens an element. That is, removes it and replace it with its children. * @param {Element} element The element to flatten. * @return {Element|undefined} The original element, detached from the document * tree, sans children, or undefined if the element was already not in the * document. */ goog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement; /** * Returns the first child node that is an element. * @param {Node} node The node to get the first child element of. * @return {Element} The first child node of {@code node} that is an element. */ goog.dom.DomHelper.prototype.getFirstElementChild = goog.dom.getFirstElementChild; /** * Returns the last child node that is an element. * @param {Node} node The node to get the last child element of. * @return {Element} The last child node of {@code node} that is an element. */ goog.dom.DomHelper.prototype.getLastElementChild = goog.dom.getLastElementChild; /** * Returns the first next sibling that is an element. * @param {Node} node The node to get the next sibling element of. * @return {Element} The next sibling of {@code node} that is an element. */ goog.dom.DomHelper.prototype.getNextElementSibling = goog.dom.getNextElementSibling; /** * Returns the first previous sibling that is an element. * @param {Node} node The node to get the previous sibling element of. * @return {Element} The first previous sibling of {@code node} that is * an element. */ goog.dom.DomHelper.prototype.getPreviousElementSibling = goog.dom.getPreviousElementSibling; /** * Whether the object looks like a DOM node. * @param {Object} obj The object being tested for node likeness. * @return {boolean} Whether the object looks like a DOM node. */ goog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike; /** * Whether a node contains another node. * @param {Node} parent The node that should contain the other node. * @param {Node} descendant The node to test presence of. * @return {boolean} Whether the parent node contains the descendent node. */ goog.dom.DomHelper.prototype.contains = goog.dom.contains; /** * Returns the owner document for a node. * @param {Node} node The node to get the document for. * @return {!Document} The document owning the node. */ goog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument; /** * Cross browser function for getting the document element of an iframe. * @param {HTMLIFrameElement|HTMLFrameElement} iframe Iframe element. * @return {!HTMLDocument} The frame content document. */ goog.dom.DomHelper.prototype.getFrameContentDocument = goog.dom.getFrameContentDocument; /** * Cross browser function for getting the window of a frame or iframe. * @param {HTMLIFrameElement|HTMLFrameElement} frame Frame element. * @return {Window} The window associated with the given frame. */ goog.dom.DomHelper.prototype.getFrameContentWindow = goog.dom.getFrameContentWindow; /** * Cross browser function for setting the text content of an element. * @param {Element} element The element to change the text content of. * @param {string} text The string that should replace the current element * content with. */ goog.dom.DomHelper.prototype.setTextContent = goog.dom.setTextContent; /** * Finds the first descendant node that matches the filter function. This does * a depth first search. * @param {Node} root The root of the tree to search. * @param {function(Node) : boolean} p The filter function. * @return {(Node, undefined)} The found node or undefined if none is found. */ goog.dom.DomHelper.prototype.findNode = goog.dom.findNode; /** * Finds all the descendant nodes that matches the filter function. This does a * depth first search. * @param {Node} root The root of the tree to search. * @param {function(Node) : boolean} p The filter function. * @return {Array.<Node>} The found nodes or an empty array if none are found. */ goog.dom.DomHelper.prototype.findNodes = goog.dom.findNodes; /** * Returns the text contents of the current node, without markup. New lines are * stripped and whitespace is collapsed, such that each character would be * visible. * * In browsers that support it, innerText is used. Other browsers attempt to * simulate it via node traversal. Line breaks are canonicalized in IE. * * @param {Node} node The node from which we are getting content. * @return {string} The text content. */ goog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent; /** * Returns the text length of the text contained in a node, without markup. This * is equivalent to the selection length if the node was selected, or the number * of cursor movements to traverse the node. Images & BRs take one space. New * lines are ignored. * * @param {Node} node The node whose text content length is being calculated. * @return {number} The length of {@code node}'s text content. */ goog.dom.DomHelper.prototype.getNodeTextLength = goog.dom.getNodeTextLength; /** * Returns the text offset of a node relative to one of its ancestors. The text * length is the same as the length calculated by * {@code goog.dom.getNodeTextLength}. * * @param {Node} node The node whose offset is being calculated. * @param {Node} opt_offsetParent Defaults to the node's owner document's body. * @return {number} The text offset. */ goog.dom.DomHelper.prototype.getNodeTextOffset = goog.dom.getNodeTextOffset; /** * Walks up the DOM hierarchy returning the first ancestor that has the passed * tag name and/or class name. If the passed element matches the specified * criteria, the element itself is returned. * @param {Node} element The DOM node to start with. * @param {?string} opt_tag The tag name to match (or null/undefined to match * any node regardless of tag name). Must be uppercase (goog.dom.TagName). * @param {?string} opt_class The class name to match (or null/undefined to * match any node regardless of class name). * @return {Node?} The first ancestor that matches the passed criteria, or * null if none match. */ goog.dom.DomHelper.prototype.getAncestorByTagNameAndClass = goog.dom.getAncestorByTagNameAndClass; /** * Walks up the DOM hierarchy returning the first ancestor that passes the * matcher function. * @param {Node} element The DOM node to start with. * @param {function(Node) : boolean} matcher A function that returns true if the * passed node matches the desired criteria. * @param {boolean} opt_includeNode If true, the node itself is included in * the search (the first call to the matcher will pass startElement as * the node to test). * @param {number} opt_maxSearchSteps Maximum number of levels to search up the * dom. * @return {Node?} DOM node that matched the matcher, or null if there was * no match. */ goog.dom.DomHelper.prototype.getAncestor = goog.dom.getAncestor;