# lib/goog/dom/dom.js

    1// Copyright 2006 The Closure Library Authors. All Rights Reserved.2//3// Licensed under the Apache License, Version 2.0 (the "License");4// you may not use this file except in compliance with the License.5// You may obtain a copy of the License at6//7//      http://www.apache.org/licenses/LICENSE-2.08//9// Unless required by applicable law or agreed to in writing, software10// distributed under the License is distributed on an "AS-IS" BASIS,11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.12// See the License for the specific language governing permissions and13// limitations under the License.1415/**16 * @fileoverview Utilities for manipulating the browser's Document Object Model17 * Inspiration taken *heavily* from mochikit (http://mochikit.com/).18 *19 * You can use {@link goog.dom.DomHelper} to create new dom helpers that refer20 * to a different document object.  This is useful if you are working with21 * frames or multiple windows.22 *23 */242526// TODO(arv): Rename/refactor getTextContent and getRawTextContent. The problem27// is that getTextContent should mimic the DOM3 textContent. We should add a28// getInnerText (or getText) which tries to return the visible text, innerText.293031goog.provide('goog.dom');32goog.provide('goog.dom.Appendable');33goog.provide('goog.dom.DomHelper');3435goog.require('goog.array');36goog.require('goog.asserts');37goog.require('goog.dom.BrowserFeature');38goog.require('goog.dom.NodeType');39goog.require('goog.dom.TagName');40goog.require('goog.math.Coordinate');41goog.require('goog.math.Size');42goog.require('goog.object');43goog.require('goog.string');44goog.require('goog.userAgent');454647/**48 * @define {boolean} Whether we know at compile time that the browser is in49 * quirks mode.50 */51goog.define('goog.dom.ASSUME_QUIRKS_MODE', false);525354/**55 * @define {boolean} Whether we know at compile time that the browser is in56 * standards compliance mode.57 */58goog.define('goog.dom.ASSUME_STANDARDS_MODE', false);596061/**62 * Whether we know the compatibility mode at compile time.63 * @type {boolean}64 * @private65 */66goog.dom.COMPAT_MODE_KNOWN_ =67    goog.dom.ASSUME_QUIRKS_MODE || goog.dom.ASSUME_STANDARDS_MODE;686970/**71 * Gets the DomHelper object for the document where the element resides.72 * @param {(Node|Window)=} opt_element If present, gets the DomHelper for this73 *     element.74 * @return {!goog.dom.DomHelper} The DomHelper.75 */76goog.dom.getDomHelper = function(opt_element) {77  return opt_element ?78      new goog.dom.DomHelper(goog.dom.getOwnerDocument(opt_element)) :79      (goog.dom.defaultDomHelper_ ||80          (goog.dom.defaultDomHelper_ = new goog.dom.DomHelper()));81};828384/**85 * Cached default DOM helper.86 * @type {goog.dom.DomHelper}87 * @private88 */89goog.dom.defaultDomHelper_;909192/**93 * Gets the document object being used by the dom library.94 * @return {!Document} Document object.95 */96goog.dom.getDocument = function() {97  return document;98};99100101/**102 * Gets an element from the current document by element id.103 *104 * If an Element is passed in, it is returned.105 *106 * @param {string|Element} element Element ID or a DOM node.107 * @return {Element} The element with the given ID, or the node passed in.108 */109goog.dom.getElement = function(element) {110  return goog.dom.getElementHelper_(document, element);111};112113114/**115 * Gets an element by id from the given document (if present).116 * If an element is given, it is returned.117 * @param {!Document} doc118 * @param {string|Element} element Element ID or a DOM node.119 * @return {Element} The resulting element.120 * @private121 */122goog.dom.getElementHelper_ = function(doc, element) {123  return goog.isString(element) ?124      doc.getElementById(element) :125      element;126};127128129/**130 * Gets an element by id, asserting that the element is found.131 *132 * This is used when an element is expected to exist, and should fail with133 * an assertion error if it does not (if assertions are enabled).134 *135 * @param {string} id Element ID.136 * @return {!Element} The element with the given ID, if it exists.137 */138goog.dom.getRequiredElement = function(id) {139  return goog.dom.getRequiredElementHelper_(document, id);140};141142143/**144 * Helper function for getRequiredElementHelper functions, both static and145 * on DomHelper.  Asserts the element with the given id exists.146 * @param {!Document} doc147 * @param {string} id148 * @return {!Element} The element with the given ID, if it exists.149 * @private150 */151goog.dom.getRequiredElementHelper_ = function(doc, id) {152  // To prevent users passing in Elements as is permitted in getElement().153  goog.asserts.assertString(id);154  var element = goog.dom.getElementHelper_(doc, id);155  element = goog.asserts.assertElement(element,156      'No element found with id: ' + id);157  return element;158};159160161/**162 * Alias for getElement.163 * @param {string|Element} element Element ID or a DOM node.164 * @return {Element} The element with the given ID, or the node passed in.165 * @deprecated Use {@link goog.dom.getElement} instead.166 */167goog.dom.$ = goog.dom.getElement;168169170/**171 * Looks up elements by both tag and class name, using browser native functions172 * ({@code querySelectorAll}, {@code getElementsByTagName} or173 * {@code getElementsByClassName}) where possible. This function174 * is a useful, if limited, way of collecting a list of DOM elements175 * with certain characteristics.  {@code goog.dom.query} offers a176 * more powerful and general solution which allows matching on CSS3177 * selector expressions, but at increased cost in code size. If all you178 * need is particular tags belonging to a single class, this function179 * is fast and sleek.180 *181 * Note that tag names are case sensitive in the SVG namespace, and this182 * function converts opt_tag to uppercase for comparisons. For queries in the183 * SVG namespace you should use querySelector or querySelectorAll instead.184 * https://bugzilla.mozilla.org/show_bug.cgi?id=963870185 * https://bugs.webkit.org/show_bug.cgi?id=83438186 *187 * @see {goog.dom.query}188 *189 * @param {?string=} opt_tag Element tag name.190 * @param {?string=} opt_class Optional class name.191 * @param {(Document|Element)=} opt_el Optional element to look in.192 * @return { {length: number} } Array-like list of elements (only a length193 *     property and numerical indices are guaranteed to exist).194 */195goog.dom.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) {196  return goog.dom.getElementsByTagNameAndClass_(document, opt_tag, opt_class,197                                                opt_el);198};199200201/**202 * Returns a static, array-like list of the elements with the provided203 * className.204 * @see {goog.dom.query}205 * @param {string} className the name of the class to look for.206 * @param {(Document|Element)=} opt_el Optional element to look in.207 * @return { {length: number} } The items found with the class name provided.208 */209goog.dom.getElementsByClass = function(className, opt_el) {210  var parent = opt_el || document;211  if (goog.dom.canUseQuerySelector_(parent)) {212    return parent.querySelectorAll('.' + className);213  }214  return goog.dom.getElementsByTagNameAndClass_(215      document, '*', className, opt_el);216};217218219/**220 * Returns the first element with the provided className.221 * @see {goog.dom.query}222 * @param {string} className the name of the class to look for.223 * @param {Element|Document=} opt_el Optional element to look in.224 * @return {Element} The first item with the class name provided.225 */226goog.dom.getElementByClass = function(className, opt_el) {227  var parent = opt_el || document;228  var retVal = null;229  if (goog.dom.canUseQuerySelector_(parent)) {230    retVal = parent.querySelector('.' + className);231  } else {232    retVal = goog.dom.getElementsByTagNameAndClass_(233        document, '*', className, opt_el)[0];234  }235  return retVal || null;236};237238239/**240 * Ensures an element with the given className exists, and then returns the241 * first element with the provided className.242 * @see {goog.dom.query}243 * @param {string} className the name of the class to look for.244 * @param {!Element|!Document=} opt_root Optional element or document to look245 *     in.246 * @return {!Element} The first item with the class name provided.247 * @throws {goog.asserts.AssertionError} Thrown if no element is found.248 */249goog.dom.getRequiredElementByClass = function(className, opt_root) {250  var retValue = goog.dom.getElementByClass(className, opt_root);251  return goog.asserts.assert(retValue,252      'No element found with className: ' + className);253};254255256/**257 * Prefer the standardized (http://www.w3.org/TR/selectors-api/), native and258 * fast W3C Selectors API.259 * @param {!(Element|Document)} parent The parent document object.260 * @return {boolean} whether or not we can use parent.querySelector* APIs.261 * @private262 */263goog.dom.canUseQuerySelector_ = function(parent) {264  return !!(parent.querySelectorAll && parent.querySelector);265};266267268/**269 * Helper for {@code getElementsByTagNameAndClass}.270 * @param {!Document} doc The document to get the elements in.271 * @param {?string=} opt_tag Element tag name.272 * @param {?string=} opt_class Optional class name.273 * @param {(Document|Element)=} opt_el Optional element to look in.274 * @return { {length: number} } Array-like list of elements (only a length275 *     property and numerical indices are guaranteed to exist).276 * @private277 */278goog.dom.getElementsByTagNameAndClass_ = function(doc, opt_tag, opt_class,279                                                  opt_el) {280  var parent = opt_el || doc;281  var tagName = (opt_tag && opt_tag != '*') ? opt_tag.toUpperCase() : '';282283  if (goog.dom.canUseQuerySelector_(parent) &&284      (tagName || opt_class)) {285    var query = tagName + (opt_class ? '.' + opt_class : '');286    return parent.querySelectorAll(query);287  }288289  // Use the native getElementsByClassName if available, under the assumption290  // that even when the tag name is specified, there will be fewer elements to291  // filter through when going by class than by tag name292  if (opt_class && parent.getElementsByClassName) {293    var els = parent.getElementsByClassName(opt_class);294295    if (tagName) {296      var arrayLike = {};297      var len = 0;298299      // Filter for specific tags if requested.300      for (var i = 0, el; el = els[i]; i++) {301        if (tagName == el.nodeName) {302          arrayLike[len++] = el;303        }304      }305      arrayLike.length = len;306307      return arrayLike;308    } else {309      return els;310    }311  }312313  var els = parent.getElementsByTagName(tagName || '*');314315  if (opt_class) {316    var arrayLike = {};317    var len = 0;318    for (var i = 0, el; el = els[i]; i++) {319      var className = el.className;320      // Check if className has a split function since SVG className does not.321      if (typeof className.split == 'function' &&322          goog.array.contains(className.split(/\s+/), opt_class)) {323        arrayLike[len++] = el;324      }325    }326    arrayLike.length = len;327    return arrayLike;328  } else {329    return els;330  }331};332333334/**335 * Alias for {@code getElementsByTagNameAndClass}.336 * @param {?string=} opt_tag Element tag name.337 * @param {?string=} opt_class Optional class name.338 * @param {Element=} opt_el Optional element to look in.339 * @return { {length: number} } Array-like list of elements (only a length340 *     property and numerical indices are guaranteed to exist).341 * @deprecated Use {@link goog.dom.getElementsByTagNameAndClass} instead.342 */343goog.dom.$$ = goog.dom.getElementsByTagNameAndClass;344345346/**347 * Sets multiple properties on a node.348 * @param {Element} element DOM node to set properties on.349 * @param {Object} properties Hash of property:value pairs.350 */351goog.dom.setProperties = function(element, properties) {352  goog.object.forEach(properties, function(val, key) {353    if (key == 'style') {354      element.style.cssText = val;355    } else if (key == 'class') {356      element.className = val;357    } else if (key == 'for') {358      element.htmlFor = val;359    } else if (key in goog.dom.DIRECT_ATTRIBUTE_MAP_) {360      element.setAttribute(goog.dom.DIRECT_ATTRIBUTE_MAP_[key], val);361    } else if (goog.string.startsWith(key, 'aria-') ||362        goog.string.startsWith(key, 'data-')) {363      element.setAttribute(key, val);364    } else {365      element[key] = val;366    }367  });368};369370371/**372 * Map of attributes that should be set using373 * element.setAttribute(key, val) instead of element[key] = val.  Used374 * by goog.dom.setProperties.375 *376 * @type {Object}377 * @private378 */379goog.dom.DIRECT_ATTRIBUTE_MAP_ = {380  'cellpadding': 'cellPadding',381  'cellspacing': 'cellSpacing',382  'colspan': 'colSpan',383  'frameborder': 'frameBorder',384  'height': 'height',385  'maxlength': 'maxLength',386  'role': 'role',387  'rowspan': 'rowSpan',388  'type': 'type',389  'usemap': 'useMap',390  'valign': 'vAlign',391  'width': 'width'392};393394395/**396 * Gets the dimensions of the viewport.397 *398 * Gecko Standards mode:399 * docEl.clientWidth  Width of viewport excluding scrollbar.400 * win.innerWidth     Width of viewport including scrollbar.401 * body.clientWidth   Width of body element.402 *403 * docEl.clientHeight Height of viewport excluding scrollbar.404 * win.innerHeight    Height of viewport including scrollbar.405 * body.clientHeight  Height of document.406 *407 * Gecko Backwards compatible mode:408 * docEl.clientWidth  Width of viewport excluding scrollbar.409 * win.innerWidth     Width of viewport including scrollbar.410 * body.clientWidth   Width of viewport excluding scrollbar.411 *412 * docEl.clientHeight Height of document.413 * win.innerHeight    Height of viewport including scrollbar.414 * body.clientHeight  Height of viewport excluding scrollbar.415 *416 * IE6/7 Standards mode:417 * docEl.clientWidth  Width of viewport excluding scrollbar.418 * win.innerWidth     Undefined.419 * body.clientWidth   Width of body element.420 *421 * docEl.clientHeight Height of viewport excluding scrollbar.422 * win.innerHeight    Undefined.423 * body.clientHeight  Height of document element.424 *425 * IE5 + IE6/7 Backwards compatible mode:426 * docEl.clientWidth  0.427 * win.innerWidth     Undefined.428 * body.clientWidth   Width of viewport excluding scrollbar.429 *430 * docEl.clientHeight 0.431 * win.innerHeight    Undefined.432 * body.clientHeight  Height of viewport excluding scrollbar.433 *434 * Opera 9 Standards and backwards compatible mode:435 * docEl.clientWidth  Width of viewport excluding scrollbar.436 * win.innerWidth     Width of viewport including scrollbar.437 * body.clientWidth   Width of viewport excluding scrollbar.438 *439 * docEl.clientHeight Height of document.440 * win.innerHeight    Height of viewport including scrollbar.441 * body.clientHeight  Height of viewport excluding scrollbar.442 *443 * WebKit:444 * Safari 2445 * docEl.clientHeight Same as scrollHeight.446 * docEl.clientWidth  Same as innerWidth.447 * win.innerWidth     Width of viewport excluding scrollbar.448 * win.innerHeight    Height of the viewport including scrollbar.449 * frame.innerHeight  Height of the viewport exluding scrollbar.450 *451 * Safari 3 (tested in 522)452 *453 * docEl.clientWidth  Width of viewport excluding scrollbar.454 * docEl.clientHeight Height of viewport excluding scrollbar in strict mode.455 * body.clientHeight  Height of viewport excluding scrollbar in quirks mode.456 *457 * @param {Window=} opt_window Optional window element to test.458 * @return {!goog.math.Size} Object with values 'width' and 'height'.459 */460goog.dom.getViewportSize = function(opt_window) {461  // TODO(arv): This should not take an argument462  return goog.dom.getViewportSize_(opt_window || window);463};464465466/**467 * Helper for {@code getViewportSize}.468 * @param {Window} win The window to get the view port size for.469 * @return {!goog.math.Size} Object with values 'width' and 'height'.470 * @private471 */472goog.dom.getViewportSize_ = function(win) {473  var doc = win.document;474  var el = goog.dom.isCss1CompatMode_(doc) ? doc.documentElement : doc.body;475  return new goog.math.Size(el.clientWidth, el.clientHeight);476};477478479/**480 * Calculates the height of the document.481 *482 * @return {number} The height of the current document.483 */484goog.dom.getDocumentHeight = function() {485  return goog.dom.getDocumentHeight_(window);486};487488489/**490 * Calculates the height of the document of the given window.491 *492 * Function code copied from the opensocial gadget api:493 *   gadgets.window.adjustHeight(opt_height)494 *495 * @private496 * @param {Window} win The window whose document height to retrieve.497 * @return {number} The height of the document of the given window.498 */499goog.dom.getDocumentHeight_ = function(win) {500  // NOTE(eae): This method will return the window size rather than the document501  // size in webkit quirks mode.502  var doc = win.document;503  var height = 0;504505  if (doc) {506    // Calculating inner content height is hard and different between507    // browsers rendering in Strict vs. Quirks mode.  We use a combination of508    // three properties within document.body and document.documentElement:509    // - scrollHeight510    // - offsetHeight511    // - clientHeight512    // These values differ significantly between browsers and rendering modes.513    // But there are patterns.  It just takes a lot of time and persistence514    // to figure out.515516    var body = doc.body;517    var docEl = doc.documentElement;518    if (!(docEl && body)) {519      return 0;520    }521522    // Get the height of the viewport523    var vh = goog.dom.getViewportSize_(win).height;524    if (goog.dom.isCss1CompatMode_(doc) && docEl.scrollHeight) {525      // In Strict mode:526      // The inner content height is contained in either:527      //    document.documentElement.scrollHeight528      //    document.documentElement.offsetHeight529      // Based on studying the values output by different browsers,530      // use the value that's NOT equal to the viewport height found above.531      height = docEl.scrollHeight != vh ?532          docEl.scrollHeight : docEl.offsetHeight;533    } else {534      // In Quirks mode:535      // documentElement.clientHeight is equal to documentElement.offsetHeight536      // except in IE.  In most browsers, document.documentElement can be used537      // to calculate the inner content height.538      // However, in other browsers (e.g. IE), document.body must be used539      // instead.  How do we know which one to use?540      // If document.documentElement.clientHeight does NOT equal541      // document.documentElement.offsetHeight, then use document.body.542      var sh = docEl.scrollHeight;543      var oh = docEl.offsetHeight;544      if (docEl.clientHeight != oh) {545        sh = body.scrollHeight;546        oh = body.offsetHeight;547      }548549      // Detect whether the inner content height is bigger or smaller550      // than the bounding box (viewport).  If bigger, take the larger551      // value.  If smaller, take the smaller value.552      if (sh > vh) {553        // Content is larger554        height = sh > oh ? sh : oh;555      } else {556        // Content is smaller557        height = sh < oh ? sh : oh;558      }559    }560  }561562  return height;563};564565566/**567 * Gets the page scroll distance as a coordinate object.568 *569 * @param {Window=} opt_window Optional window element to test.570 * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.571 * @deprecated Use {@link goog.dom.getDocumentScroll} instead.572 */573goog.dom.getPageScroll = function(opt_window) {574  var win = opt_window || goog.global || window;575  return goog.dom.getDomHelper(win.document).getDocumentScroll();576};577578579/**580 * Gets the document scroll distance as a coordinate object.581 *582 * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.583 */584goog.dom.getDocumentScroll = function() {585  return goog.dom.getDocumentScroll_(document);586};587588589/**590 * Helper for {@code getDocumentScroll}.591 *592 * @param {!Document} doc The document to get the scroll for.593 * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.594 * @private595 */596goog.dom.getDocumentScroll_ = function(doc) {597  var el = goog.dom.getDocumentScrollElement_(doc);598  var win = goog.dom.getWindow_(doc);599  if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('10') &&600      win.pageYOffset != el.scrollTop) {601    // The keyboard on IE10 touch devices shifts the page using the pageYOffset602    // without modifying scrollTop. For this case, we want the body scroll603    // offsets.604    return new goog.math.Coordinate(el.scrollLeft, el.scrollTop);605  }606  return new goog.math.Coordinate(win.pageXOffset || el.scrollLeft,607      win.pageYOffset || el.scrollTop);608};609610611/**612 * Gets the document scroll element.613 * @return {!Element} Scrolling element.614 */615goog.dom.getDocumentScrollElement = function() {616  return goog.dom.getDocumentScrollElement_(document);617};618619620/**621 * Helper for {@code getDocumentScrollElement}.622 * @param {!Document} doc The document to get the scroll element for.623 * @return {!Element} Scrolling element.624 * @private625 */626goog.dom.getDocumentScrollElement_ = function(doc) {627  // WebKit needs body.scrollLeft in both quirks mode and strict mode. We also628  // default to the documentElement if the document does not have a body (e.g.629  // a SVG document).630  if (!goog.userAgent.WEBKIT && goog.dom.isCss1CompatMode_(doc)) {631    return doc.documentElement;632  }633  return doc.body || doc.documentElement;634};635636637/**638 * Gets the window object associated with the given document.639 *640 * @param {Document=} opt_doc  Document object to get window for.641 * @return {!Window} The window associated with the given document.642 */643goog.dom.getWindow = function(opt_doc) {644  // TODO(arv): This should not take an argument.645  return opt_doc ? goog.dom.getWindow_(opt_doc) : window;646};647648649/**650 * Helper for {@code getWindow}.651 *652 * @param {!Document} doc  Document object to get window for.653 * @return {!Window} The window associated with the given document.654 * @private655 */656goog.dom.getWindow_ = function(doc) {657  return doc.parentWindow || doc.defaultView;658};659660661/**662 * Returns a dom node with a set of attributes.  This function accepts varargs663 * for subsequent nodes to be added.  Subsequent nodes will be added to the664 * first node as childNodes.665 *666 * So:667 * <code>createDom('div', null, createDom('p'), createDom('p'));</code>668 * would return a div with two child paragraphs669 *670 * @param {string} tagName Tag to create.671 * @param {(Object|Array.<string>|string)=} opt_attributes If object, then a map672 *     of name-value pairs for attributes. If a string, then this is the673 *     className of the new element. If an array, the elements will be joined674 *     together as the className of the new element.675 * @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or676 *     strings for text nodes. If one of the var_args is an array or NodeList,i677 *     its elements will be added as childNodes instead.678 * @return {!Element} Reference to a DOM node.679 */680goog.dom.createDom = function(tagName, opt_attributes, var_args) {681  return goog.dom.createDom_(document, arguments);682};683684685/**686 * Helper for {@code createDom}.687 * @param {!Document} doc The document to create the DOM in.688 * @param {!Arguments} args Argument object passed from the callers. See689 *     {@code goog.dom.createDom} for details.690 * @return {!Element} Reference to a DOM node.691 * @private692 */693goog.dom.createDom_ = function(doc, args) {694  var tagName = args[0];695  var attributes = args[1];696697  // Internet Explorer is dumb: http://msdn.microsoft.com/workshop/author/698  //                            dhtml/reference/properties/name_2.asp699  // Also does not allow setting of 'type' attribute on 'input' or 'button'.700  if (!goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES && attributes &&701      (attributes.name || attributes.type)) {702    var tagNameArr = ['<', tagName];703    if (attributes.name) {704      tagNameArr.push(' name="', goog.string.htmlEscape(attributes.name),705                      '"');706    }707    if (attributes.type) {708      tagNameArr.push(' type="', goog.string.htmlEscape(attributes.type),709                      '"');710711      // Clone attributes map to remove 'type' without mutating the input.712      var clone = {};713      goog.object.extend(clone, attributes);714715      // JSCompiler can't see how goog.object.extend added this property,716      // because it was essentially added by reflection.717      // So it needs to be quoted.718      delete clone['type'];719720      attributes = clone;721    }722    tagNameArr.push('>');723    tagName = tagNameArr.join('');724  }725726  var element = doc.createElement(tagName);727728  if (attributes) {729    if (goog.isString(attributes)) {730      element.className = attributes;731    } else if (goog.isArray(attributes)) {732      element.className = attributes.join(' ');733    } else {734      goog.dom.setProperties(element, attributes);735    }736  }737738  if (args.length > 2) {739    goog.dom.append_(doc, element, args, 2);740  }741742  return element;743};744745746/**747 * Appends a node with text or other nodes.748 * @param {!Document} doc The document to create new nodes in.749 * @param {!Node} parent The node to append nodes to.750 * @param {!Arguments} args The values to add. See {@code goog.dom.append}.751 * @param {number} startIndex The index of the array to start from.752 * @private753 */754goog.dom.append_ = function(doc, parent, args, startIndex) {755  function childHandler(child) {756    // TODO(user): More coercion, ala MochiKit?757    if (child) {758      parent.appendChild(goog.isString(child) ?759          doc.createTextNode(child) : child);760    }761  }762763  for (var i = startIndex; i < args.length; i++) {764    var arg = args[i];765    // TODO(attila): Fix isArrayLike to return false for a text node.766    if (goog.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) {767      // If the argument is a node list, not a real array, use a clone,768      // because forEach can't be used to mutate a NodeList.769      goog.array.forEach(goog.dom.isNodeList(arg) ?770          goog.array.toArray(arg) : arg,771          childHandler);772    } else {773      childHandler(arg);774    }775  }776};777778779/**780 * Alias for {@code createDom}.781 * @param {string} tagName Tag to create.782 * @param {(string|Object)=} opt_attributes If object, then a map of name-value783 *     pairs for attributes. If a string, then this is the className of the new784 *     element.785 * @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or786 *     strings for text nodes. If one of the var_args is an array, its787 *     children will be added as childNodes instead.788 * @return {!Element} Reference to a DOM node.789 * @deprecated Use {@link goog.dom.createDom} instead.790 */791goog.dom.$dom = goog.dom.createDom;792793794/**795 * Creates a new element.796 * @param {string} name Tag name.797 * @return {!Element} The new element.798 */799goog.dom.createElement = function(name) {800  return document.createElement(name);801};802803804/**805 * Creates a new text node.806 * @param {number|string} content Content.807 * @return {!Text} The new text node.808 */809goog.dom.createTextNode = function(content) {810  return document.createTextNode(String(content));811};812813814/**815 * Create a table.816 * @param {number} rows The number of rows in the table.  Must be >= 1.817 * @param {number} columns The number of columns in the table.  Must be >= 1.818 * @param {boolean=} opt_fillWithNbsp If true, fills table entries with nsbps.819 * @return {!Element} The created table.820 */821goog.dom.createTable = function(rows, columns, opt_fillWithNbsp) {822  return goog.dom.createTable_(document, rows, columns, !!opt_fillWithNbsp);823};824825826/**827 * Create a table.828 * @param {!Document} doc Document object to use to create the table.829 * @param {number} rows The number of rows in the table.  Must be >= 1.830 * @param {number} columns The number of columns in the table.  Must be >= 1.831 * @param {boolean} fillWithNbsp If true, fills table entries with nsbps.832 * @return {!Element} The created table.833 * @private834 */835goog.dom.createTable_ = function(doc, rows, columns, fillWithNbsp) {836  var rowHtml = ['<tr>'];837  for (var i = 0; i < columns; i++) {838    rowHtml.push(fillWithNbsp ? '<td>&nbsp;</td>' : '<td></td>');839  }840  rowHtml.push('</tr>');841  rowHtml = rowHtml.join('');842  var totalHtml = ['<table>'];843  for (i = 0; i < rows; i++) {844    totalHtml.push(rowHtml);845  }846  totalHtml.push('</table>');847848  var elem = doc.createElement(goog.dom.TagName.DIV);849  elem.innerHTML = totalHtml.join('');850  return /** @type {!Element} */ (elem.removeChild(elem.firstChild));851};852853854/**855 * Converts an HTML string into a document fragment. The string must be856 * sanitized in order to avoid cross-site scripting. For example857 * {@code goog.dom.htmlToDocumentFragment('&lt;img src=x onerror=alert(0)&gt;')}858 * triggers an alert in all browsers, even if the returned document fragment859 * is thrown away immediately.860 *861 * @param {string} htmlString The HTML string to convert.862 * @return {!Node} The resulting document fragment.863 */864goog.dom.htmlToDocumentFragment = function(htmlString) {865  return goog.dom.htmlToDocumentFragment_(document, htmlString);866};867868869/**870 * Helper for {@code htmlToDocumentFragment}.871 *872 * @param {!Document} doc The document.873 * @param {string} htmlString The HTML string to convert.874 * @return {!Node} The resulting document fragment.875 * @private876 */877goog.dom.htmlToDocumentFragment_ = function(doc, htmlString) {878  var tempDiv = doc.createElement('div');879  if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) {880    tempDiv.innerHTML = '<br>' + htmlString;881    tempDiv.removeChild(tempDiv.firstChild);882  } else {883    tempDiv.innerHTML = htmlString;884  }885  if (tempDiv.childNodes.length == 1) {886    return /** @type {!Node} */ (tempDiv.removeChild(tempDiv.firstChild));887  } else {888    var fragment = doc.createDocumentFragment();889    while (tempDiv.firstChild) {890      fragment.appendChild(tempDiv.firstChild);891    }892    return fragment;893  }894};895896897/**898 * Returns true if the browser is in "CSS1-compatible" (standards-compliant)899 * mode, false otherwise.900 * @return {boolean} True if in CSS1-compatible mode.901 */902goog.dom.isCss1CompatMode = function() {903  return goog.dom.isCss1CompatMode_(document);904};905906907/**908 * Returns true if the browser is in "CSS1-compatible" (standards-compliant)909 * mode, false otherwise.910 * @param {Document} doc The document to check.911 * @return {boolean} True if in CSS1-compatible mode.912 * @private913 */914goog.dom.isCss1CompatMode_ = function(doc) {915  if (goog.dom.COMPAT_MODE_KNOWN_) {916    return goog.dom.ASSUME_STANDARDS_MODE;917  }918919  return doc.compatMode == 'CSS1Compat';920};921922923/**924 * Determines if the given node can contain children, intended to be used for925 * HTML generation.926 *927 * IE natively supports node.canHaveChildren but has inconsistent behavior.928 * Prior to IE8 the base tag allows children and in IE9 all nodes return true929 * for canHaveChildren.930 *931 * In practice all non-IE browsers allow you to add children to any node, but932 * the behavior is inconsistent:933 *934 * <pre>935 *   var a = document.createElement('br');936 *   a.appendChild(document.createTextNode('foo'));937 *   a.appendChild(document.createTextNode('bar'));938 *   console.log(a.childNodes.length);  // 2939 *   console.log(a.innerHTML);  // Chrome: "", IE9: "foobar", FF3.5: "foobar"940 * </pre>941 *942 * For more information, see:943 * http://dev.w3.org/html5/markup/syntax.html#syntax-elements944 *945 * TODO(user): Rename shouldAllowChildren() ?946 *947 * @param {Node} node The node to check.948 * @return {boolean} Whether the node can contain children.949 */950goog.dom.canHaveChildren = function(node) {951  if (node.nodeType != goog.dom.NodeType.ELEMENT) {952    return false;953  }954  switch (node.tagName) {955    case goog.dom.TagName.APPLET:956    case goog.dom.TagName.AREA:957    case goog.dom.TagName.BASE:958    case goog.dom.TagName.BR:959    case goog.dom.TagName.COL:960    case goog.dom.TagName.COMMAND:961    case goog.dom.TagName.EMBED:962    case goog.dom.TagName.FRAME:963    case goog.dom.TagName.HR:964    case goog.dom.TagName.IMG:965    case goog.dom.TagName.INPUT:966    case goog.dom.TagName.IFRAME:967    case goog.dom.TagName.ISINDEX:968    case goog.dom.TagName.KEYGEN:969    case goog.dom.TagName.LINK:970    case goog.dom.TagName.NOFRAMES:971    case goog.dom.TagName.NOSCRIPT:972    case goog.dom.TagName.META:973    case goog.dom.TagName.OBJECT:974    case goog.dom.TagName.PARAM:975    case goog.dom.TagName.SCRIPT:976    case goog.dom.TagName.SOURCE:977    case goog.dom.TagName.STYLE:978    case goog.dom.TagName.TRACK:979    case goog.dom.TagName.WBR:980      return false;981  }982  return true;983};984985986/**987 * Appends a child to a node.988 * @param {Node} parent Parent.989 * @param {Node} child Child.990 */991goog.dom.appendChild = function(parent, child) {992  parent.appendChild(child);993};994995996/**997 * Appends a node with text or other nodes.998 * @param {!Node} parent The node to append nodes to.999 * @param {...goog.dom.Appendable} var_args The things to append to the node.1000 *     If this is a Node it is appended as is.1001 *     If this is a string then a text node is appended.1002 *     If this is an array like object then fields 0 to length - 1 are appended.1003 */1004goog.dom.append = function(parent, var_args) {1005  goog.dom.append_(goog.dom.getOwnerDocument(parent), parent, arguments, 1);1006};100710081009/**1010 * Removes all the child nodes on a DOM node.1011 * @param {Node} node Node to remove children from.1012 */1013goog.dom.removeChildren = function(node) {1014  // Note: Iterations over live collections can be slow, this is the fastest1015  // we could find. The double parenthesis are used to prevent JsCompiler and1016  // strict warnings.1017  var child;1018  while ((child = node.firstChild)) {1019    node.removeChild(child);1020  }1021};102210231024/**1025 * Inserts a new node before an existing reference node (i.e. as the previous1026 * sibling). If the reference node has no parent, then does nothing.1027 * @param {Node} newNode Node to insert.1028 * @param {Node} refNode Reference node to insert before.1029 */1030goog.dom.insertSiblingBefore = function(newNode, refNode) {1031  if (refNode.parentNode) {1032    refNode.parentNode.insertBefore(newNode, refNode);1033  }1034};103510361037/**1038 * Inserts a new node after an existing reference node (i.e. as the next1039 * sibling). If the reference node has no parent, then does nothing.1040 * @param {Node} newNode Node to insert.1041 * @param {Node} refNode Reference node to insert after.1042 */1043goog.dom.insertSiblingAfter = function(newNode, refNode) {1044  if (refNode.parentNode) {1045    refNode.parentNode.insertBefore(newNode, refNode.nextSibling);1046  }1047};104810491050/**1051 * Insert a child at a given index. If index is larger than the number of child1052 * nodes that the parent currently has, the node is inserted as the last child1053 * node.1054 * @param {Element} parent The element into which to insert the child.1055 * @param {Node} child The element to insert.1056 * @param {number} index The index at which to insert the new child node. Must1057 *     not be negative.1058 */1059goog.dom.insertChildAt = function(parent, child, index) {1060  // Note that if the second argument is null, insertBefore1061  // will append the child at the end of the list of children.1062  parent.insertBefore(child, parent.childNodes[index] || null);1063};106410651066/**1067 * Removes a node from its parent.1068 * @param {Node} node The node to remove.1069 * @return {Node} The node removed if removed; else, null.1070 */1071goog.dom.removeNode = function(node) {1072  return node && node.parentNode ? node.parentNode.removeChild(node) : null;1073};107410751076/**1077 * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no1078 * parent.1079 * @param {Node} newNode Node to insert.1080 * @param {Node} oldNode Node to replace.1081 */1082goog.dom.replaceNode = function(newNode, oldNode) {1083  var parent = oldNode.parentNode;1084  if (parent) {1085    parent.replaceChild(newNode, oldNode);1086  }1087};108810891090/**1091 * Flattens an element. That is, removes it and replace it with its children.1092 * Does nothing if the element is not in the document.1093 * @param {Element} element The element to flatten.1094 * @return {Element|undefined} The original element, detached from the document1095 *     tree, sans children; or undefined, if the element was not in the document1096 *     to begin with.1097 */1098goog.dom.flattenElement = function(element) {1099  var child, parent = element.parentNode;1100  if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) {1101    // Use IE DOM method (supported by Opera too) if available1102    if (element.removeNode) {1103      return /** @type {Element} */ (element.removeNode(false));1104    } else {1105      // Move all children of the original node up one level.1106      while ((child = element.firstChild)) {1107        parent.insertBefore(child, element);1108      }11091110      // Detach the original element.1111      return /** @type {Element} */ (goog.dom.removeNode(element));1112    }1113  }1114};111511161117/**1118 * Returns an array containing just the element children of the given element.1119 * @param {Element} element The element whose element children we want.1120 * @return {!(Array|NodeList)} An array or array-like list of just the element1121 *     children of the given element.1122 */1123goog.dom.getChildren = function(element) {1124  // We check if the children attribute is supported for child elements1125  // since IE8 misuses the attribute by also including comments.1126  if (goog.dom.BrowserFeature.CAN_USE_CHILDREN_ATTRIBUTE &&1127      element.children != undefined) {1128    return element.children;1129  }1130  // Fall back to manually filtering the element's child nodes.1131  return goog.array.filter(element.childNodes, function(node) {1132    return node.nodeType == goog.dom.NodeType.ELEMENT;1133  });1134};113511361137/**1138 * Returns the first child node that is an element.1139 * @param {Node} node The node to get the first child element of.1140 * @return {Element} The first child node of {@code node} that is an element.1141 */1142goog.dom.getFirstElementChild = function(node) {1143  if (node.firstElementChild != undefined) {1144    return /** @type {Element} */(node).firstElementChild;1145  }1146  return goog.dom.getNextElementNode_(node.firstChild, true);1147};114811491150/**1151 * Returns the last child node that is an element.1152 * @param {Node} node The node to get the last child element of.1153 * @return {Element} The last child node of {@code node} that is an element.1154 */1155goog.dom.getLastElementChild = function(node) {1156  if (node.lastElementChild != undefined) {1157    return /** @type {Element} */(node).lastElementChild;1158  }1159  return goog.dom.getNextElementNode_(node.lastChild, false);1160};116111621163/**1164 * Returns the first next sibling that is an element.1165 * @param {Node} node The node to get the next sibling element of.1166 * @return {Element} The next sibling of {@code node} that is an element.1167 */1168goog.dom.getNextElementSibling = function(node) {1169  if (node.nextElementSibling != undefined) {1170    return /** @type {Element} */(node).nextElementSibling;1171  }1172  return goog.dom.getNextElementNode_(node.nextSibling, true);1173};117411751176/**1177 * Returns the first previous sibling that is an element.1178 * @param {Node} node The node to get the previous sibling element of.1179 * @return {Element} The first previous sibling of {@code node} that is1180 *     an element.1181 */1182goog.dom.getPreviousElementSibling = function(node) {1183  if (node.previousElementSibling != undefined) {1184    return /** @type {Element} */(node).previousElementSibling;1185  }1186  return goog.dom.getNextElementNode_(node.previousSibling, false);1187};118811891190/**1191 * Returns the first node that is an element in the specified direction,1192 * starting with {@code node}.1193 * @param {Node} node The node to get the next element from.1194 * @param {boolean} forward Whether to look forwards or backwards.1195 * @return {Element} The first element.1196 * @private1197 */1198goog.dom.getNextElementNode_ = function(node, forward) {1199  while (node && node.nodeType != goog.dom.NodeType.ELEMENT) {1200    node = forward ? node.nextSibling : node.previousSibling;1201  }12021203  return /** @type {Element} */ (node);1204};120512061207/**1208 * Returns the next node in source order from the given node.1209 * @param {Node} node The node.1210 * @return {Node} The next node in the DOM tree, or null if this was the last1211 *     node.1212 */1213goog.dom.getNextNode = function(node) {1214  if (!node) {1215    return null;1216  }12171218  if (node.firstChild) {1219    return node.firstChild;1220  }12211222  while (node && !node.nextSibling) {1223    node = node.parentNode;1224  }12251226  return node ? node.nextSibling : null;1227};122812291230/**1231 * Returns the previous node in source order from the given node.1232 * @param {Node} node The node.1233 * @return {Node} The previous node in the DOM tree, or null if this was the1234 *     first node.1235 */1236goog.dom.getPreviousNode = function(node) {1237  if (!node) {1238    return null;1239  }12401241  if (!node.previousSibling) {1242    return node.parentNode;1243  }12441245  node = node.previousSibling;1246  while (node && node.lastChild) {1247    node = node.lastChild;1248  }12491250  return node;1251};125212531254/**1255 * Whether the object looks like a DOM node.1256 * @param {?} obj The object being tested for node likeness.1257 * @return {boolean} Whether the object looks like a DOM node.1258 */1259goog.dom.isNodeLike = function(obj) {1260  return goog.isObject(obj) && obj.nodeType > 0;1261};126212631264/**1265 * Whether the object looks like an Element.1266 * @param {?} obj The object being tested for Element likeness.1267 * @return {boolean} Whether the object looks like an Element.1268 */1269goog.dom.isElement = function(obj) {1270  return goog.isObject(obj) && obj.nodeType == goog.dom.NodeType.ELEMENT;1271};127212731274/**1275 * Returns true if the specified value is a Window object. This includes the1276 * global window for HTML pages, and iframe windows.1277 * @param {?} obj Variable to test.1278 * @return {boolean} Whether the variable is a window.1279 */1280goog.dom.isWindow = function(obj) {1281  return goog.isObject(obj) && obj['window'] == obj;1282};128312841285/**1286 * Returns an element's parent, if it's an Element.1287 * @param {Element} element The DOM element.1288 * @return {Element} The parent, or null if not an Element.1289 */1290goog.dom.getParentElement = function(element) {1291  var parent;1292  if (goog.dom.BrowserFeature.CAN_USE_PARENT_ELEMENT_PROPERTY) {1293    var isIe9 = goog.userAgent.IE &&1294        goog.userAgent.isVersionOrHigher('9') &&1295        !goog.userAgent.isVersionOrHigher('10');1296    // SVG elements in IE9 can't use the parentElement property.1297    // goog.global['SVGElement'] is not defined in IE9 quirks mode.1298    if (!(isIe9 && goog.global['SVGElement'] &&1299        element instanceof goog.global['SVGElement'])) {1300      parent = element.parentElement;1301      if (parent) {1302        return parent;1303      }1304    }1305  }1306  parent = element.parentNode;1307  return goog.dom.isElement(parent) ? /** @type {!Element} */ (parent) : null;1308};130913101311/**1312 * Whether a node contains another node.1313 * @param {Node} parent The node that should contain the other node.1314 * @param {Node} descendant The node to test presence of.1315 * @return {boolean} Whether the parent node contains the descendent node.1316 */1317goog.dom.contains = function(parent, descendant) {1318  // We use browser specific methods for this if available since it is faster1319  // that way.13201321  // IE DOM1322  if (parent.contains && descendant.nodeType == goog.dom.NodeType.ELEMENT) {1323    return parent == descendant || parent.contains(descendant);1324  }13251326  // W3C DOM Level 31327  if (typeof parent.compareDocumentPosition != 'undefined') {1328    return parent == descendant ||1329        Boolean(parent.compareDocumentPosition(descendant) & 16);1330  }13311332  // W3C DOM Level 11333  while (descendant && parent != descendant) {1334    descendant = descendant.parentNode;1335  }1336  return descendant == parent;1337};133813391340/**1341 * Compares the document order of two nodes, returning 0 if they are the same1342 * node, a negative number if node1 is before node2, and a positive number if1343 * node2 is before node1.  Note that we compare the order the tags appear in the1344 * document so in the tree <b><i>text</i></b> the B node is considered to be1345 * before the I node.1346 *1347 * @param {Node} node1 The first node to compare.1348 * @param {Node} node2 The second node to compare.1349 * @return {number} 0 if the nodes are the same node, a negative number if node11350 *     is before node2, and a positive number if node2 is before node1.1351 */1352goog.dom.compareNodeOrder = function(node1, node2) {1353  // Fall out quickly for equality.1354  if (node1 == node2) {1355    return 0;1356  }13571358  // Use compareDocumentPosition where available1359  if (node1.compareDocumentPosition) {1360    // 4 is the bitmask for FOLLOWS.1361    return node1.compareDocumentPosition(node2) & 2 ? 1 : -1;1362  }13631364  // Special case for document nodes on IE 7 and 8.1365  if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) {1366    if (node1.nodeType == goog.dom.NodeType.DOCUMENT) {1367      return -1;1368    }1369    if (node2.nodeType == goog.dom.NodeType.DOCUMENT) {1370      return 1;1371    }1372  }13731374  // Process in IE using sourceIndex - we check to see if the first node has1375  // a source index or if its parent has one.1376  if ('sourceIndex' in node1 ||1377      (node1.parentNode && 'sourceIndex' in node1.parentNode)) {1378    var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT;1379    var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT;13801381    if (isElement1 && isElement2) {1382      return node1.sourceIndex - node2.sourceIndex;1383    } else {1384      var parent1 = node1.parentNode;1385      var parent2 = node2.parentNode;13861387      if (parent1 == parent2) {1388        return goog.dom.compareSiblingOrder_(node1, node2);1389      }13901391      if (!isElement1 && goog.dom.contains(parent1, node2)) {1392        return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2);1393      }139413951396      if (!isElement2 && goog.dom.contains(parent2, node1)) {1397        return goog.dom.compareParentsDescendantNodeIe_(node2, node1);1398      }13991400      return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) -1401             (isElement2 ? node2.sourceIndex : parent2.sourceIndex);1402    }1403  }14041405  // For Safari, we compare ranges.1406  var doc = goog.dom.getOwnerDocument(node1);14071408  var range1, range2;1409  range1 = doc.createRange();1410  range1.selectNode(node1);1411  range1.collapse(true);14121413  range2 = doc.createRange();1414  range2.selectNode(node2);1415  range2.collapse(true);14161417  return range1.compareBoundaryPoints(goog.global['Range'].START_TO_END,1418      range2);1419};142014211422/**1423 * Utility function to compare the position of two nodes, when1424 * {@code textNode}'s parent is an ancestor of {@code node}.  If this entry1425 * condition is not met, this function will attempt to reference a null object.1426 * @param {Node} textNode The textNode to compare.1427 * @param {Node} node The node to compare.1428 * @return {number} -1 if node is before textNode, +1 otherwise.1429 * @private1430 */1431goog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) {1432  var parent = textNode.parentNode;1433  if (parent == node) {1434    // If textNode is a child of node, then node comes first.1435    return -1;1436  }1437  var sibling = node;1438  while (sibling.parentNode != parent) {1439    sibling = sibling.parentNode;1440  }1441  return goog.dom.compareSiblingOrder_(sibling, textNode);1442};144314441445/**1446 * Utility function to compare the position of two nodes known to be non-equal1447 * siblings.1448 * @param {Node} node1 The first node to compare.1449 * @param {Node} node2 The second node to compare.1450 * @return {number} -1 if node1 is before node2, +1 otherwise.1451 * @private1452 */1453goog.dom.compareSiblingOrder_ = function(node1, node2) {1454  var s = node2;1455  while ((s = s.previousSibling)) {1456    if (s == node1) {1457      // We just found node1 before node2.1458      return -1;1459    }1460  }14611462  // Since we didn't find it, node1 must be after node2.1463  return 1;1464};146514661467/**1468 * Find the deepest common ancestor of the given nodes.1469 * @param {...Node} var_args The nodes to find a common ancestor of.1470 * @return {Node} The common ancestor of the nodes, or null if there is none.1471 *     null will only be returned if two or more of the nodes are from different1472 *     documents.1473 */1474goog.dom.findCommonAncestor = function(var_args) {1475  var i, count = arguments.length;1476  if (!count) {1477    return null;1478  } else if (count == 1) {1479    return arguments[0];1480  }14811482  var paths = [];1483  var minLength = Infinity;1484  for (i = 0; i < count; i++) {1485    // Compute the list of ancestors.1486    var ancestors = [];1487    var node = arguments[i];1488    while (node) {1489      ancestors.unshift(node);1490      node = node.parentNode;1491    }14921493    // Save the list for comparison.1494    paths.push(ancestors);1495    minLength = Math.min(minLength, ancestors.length);1496  }1497  var output = null;1498  for (i = 0; i < minLength; i++) {1499    var first = paths[0][i];1500    for (var j = 1; j < count; j++) {1501      if (first != paths[j][i]) {1502        return output;1503      }1504    }1505    output = first;1506  }1507  return output;1508};150915101511/**1512 * Returns the owner document for a node.1513 * @param {Node|Window} node The node to get the document for.1514 * @return {!Document} The document owning the node.1515 */1516goog.dom.getOwnerDocument = function(node) {1517  // TODO(nnaze): Update param signature to be non-nullable.1518  goog.asserts.assert(node, 'Node cannot be null or undefined.');1519  return /** @type {!Document} */ (1520      node.nodeType == goog.dom.NodeType.DOCUMENT ? node :1521      node.ownerDocument || node.document);1522};152315241525/**1526 * Cross-browser function for getting the document element of a frame or iframe.1527 * @param {Element} frame Frame element.1528 * @return {!Document} The frame content document.1529 */1530goog.dom.getFrameContentDocument = function(frame) {1531  var doc = frame.contentDocument || frame.contentWindow.document;1532  return doc;1533};153415351536/**1537 * Cross-browser function for getting the window of a frame or iframe.1538 * @param {Element} frame Frame element.1539 * @return {Window} The window associated with the given frame.1540 */1541goog.dom.getFrameContentWindow = function(frame) {1542  return frame.contentWindow ||1543      goog.dom.getWindow(goog.dom.getFrameContentDocument(frame));1544};154515461547/**1548 * Sets the text content of a node, with cross-browser support.1549 * @param {Node} node The node to change the text content of.1550 * @param {string|number} text The value that should replace the node's content.1551 */1552goog.dom.setTextContent = function(node, text) {1553  goog.asserts.assert(node != null,1554      'goog.dom.setTextContent expects a non-null value for node');15551556  if ('textContent' in node) {1557    node.textContent = text;1558  } else if (node.nodeType == goog.dom.NodeType.TEXT) {1559    node.data = text;1560  } else if (node.firstChild &&1561             node.firstChild.nodeType == goog.dom.NodeType.TEXT) {1562    // If the first child is a text node we just change its data and remove the1563    // rest of the children.1564    while (node.lastChild != node.firstChild) {1565      node.removeChild(node.lastChild);1566    }1567    node.firstChild.data = text;1568  } else {1569    goog.dom.removeChildren(node);1570    var doc = goog.dom.getOwnerDocument(node);1571    node.appendChild(doc.createTextNode(String(text)));1572  }1573};157415751576/**1577 * Gets the outerHTML of a node, which islike innerHTML, except that it1578 * actually contains the HTML of the node itself.1579 * @param {Element} element The element to get the HTML of.1580 * @return {string} The outerHTML of the given element.1581 */1582goog.dom.getOuterHtml = function(element) {1583  // IE, Opera and WebKit all have outerHTML.1584  if ('outerHTML' in element) {1585    return element.outerHTML;1586  } else {1587    var doc = goog.dom.getOwnerDocument(element);1588    var div = doc.createElement('div');1589    div.appendChild(element.cloneNode(true));1590    return div.innerHTML;1591  }1592};159315941595/**1596 * Finds the first descendant node that matches the filter function, using1597 * a depth first search. This function offers the most general purpose way1598 * of finding a matching element. You may also wish to consider1599 * {@code goog.dom.query} which can express many matching criteria using1600 * CSS selector expressions. These expressions often result in a more1601 * compact representation of the desired result.1602 * @see goog.dom.query1603 *1604 * @param {Node} root The root of the tree to search.1605 * @param {function(Node) : boolean} p The filter function.1606 * @return {Node|undefined} The found node or undefined if none is found.1607 */1608goog.dom.findNode = function(root, p) {1609  var rv = [];1610  var found = goog.dom.findNodes_(root, p, rv, true);1611  return found ? rv[0] : undefined;1612};161316141615/**1616 * Finds all the descendant nodes that match the filter function, using a1617 * a depth first search. This function offers the most general-purpose way1618 * of finding a set of matching elements. You may also wish to consider1619 * {@code goog.dom.query} which can express many matching criteria using1620 * CSS selector expressions. These expressions often result in a more1621 * compact representation of the desired result.16221623 * @param {Node} root The root of the tree to search.1624 * @param {function(Node) : boolean} p The filter function.1625 * @return {!Array.<!Node>} The found nodes or an empty array if none are found.1626 */1627goog.dom.findNodes = function(root, p) {1628  var rv = [];1629  goog.dom.findNodes_(root, p, rv, false);1630  return rv;1631};163216331634/**1635 * Finds the first or all the descendant nodes that match the filter function,1636 * using a depth first search.1637 * @param {Node} root The root of the tree to search.1638 * @param {function(Node) : boolean} p The filter function.1639 * @param {!Array.<!Node>} rv The found nodes are added to this array.1640 * @param {boolean} findOne If true we exit after the first found node.1641 * @return {boolean} Whether the search is complete or not. True in case findOne1642 *     is true and the node is found. False otherwise.1643 * @private1644 */1645goog.dom.findNodes_ = function(root, p, rv, findOne) {1646  if (root != null) {1647    var child = root.firstChild;1648    while (child) {1649      if (p(child)) {1650        rv.push(child);1651        if (findOne) {1652          return true;1653        }1654      }1655      if (goog.dom.findNodes_(child, p, rv, findOne)) {1656        return true;1657      }1658      child = child.nextSibling;1659    }1660  }1661  return false;1662};166316641665/**1666 * Map of tags whose content to ignore when calculating text length.1667 * @type {Object}1668 * @private1669 */1670goog.dom.TAGS_TO_IGNORE_ = {1671  'SCRIPT': 1,1672  'STYLE': 1,1673  'HEAD': 1,1674  'IFRAME': 1,1675  'OBJECT': 11676};167716781679/**1680 * Map of tags which have predefined values with regard to whitespace.1681 * @type {Object}1682 * @private1683 */1684goog.dom.PREDEFINED_TAG_VALUES_ = {'IMG': ' ', 'BR': '\n'};168516861687/**1688 * Returns true if the element has a tab index that allows it to receive1689 * keyboard focus (tabIndex >= 0), false otherwise.  Note that some elements1690 * natively support keyboard focus, even if they have no tab index.1691 * @param {Element} element Element to check.1692 * @return {boolean} Whether the element has a tab index that allows keyboard1693 *     focus.1694 * @see http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/1695 */1696goog.dom.isFocusableTabIndex = function(element) {1697  return goog.dom.hasSpecifiedTabIndex_(element) &&1698         goog.dom.isTabIndexFocusable_(element);1699};170017011702/**1703 * Enables or disables keyboard focus support on the element via its tab index.1704 * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true1705 * (or elements that natively support keyboard focus, like form elements) can1706 * receive keyboard focus.  See http://go/tabindex for more info.1707 * @param {Element} element Element whose tab index is to be changed.1708 * @param {boolean} enable Whether to set or remove a tab index on the element1709 *     that supports keyboard focus.1710 */1711goog.dom.setFocusableTabIndex = function(element, enable) {1712  if (enable) {1713    element.tabIndex = 0;1714  } else {1715    // Set tabIndex to -1 first, then remove it. This is a workaround for1716    // Safari (confirmed in version 4 on Windows). When removing the attribute1717    // without setting it to -1 first, the element remains keyboard focusable1718    // despite not having a tabIndex attribute anymore.1719    element.tabIndex = -1;1720    element.removeAttribute('tabIndex'); // Must be camelCase!1721  }1722};172317241725/**1726 * Returns true if the element can be focused, i.e. it has a tab index that1727 * allows it to receive keyboard focus (tabIndex >= 0), or it is an element1728 * that natively supports keyboard focus.1729 * @param {Element} element Element to check.1730 * @return {boolean} Whether the element allows keyboard focus.1731 */1732goog.dom.isFocusable = function(element) {1733  var focusable;1734  // Some elements can have unspecified tab index and still receive focus.1735  if (goog.dom.nativelySupportsFocus_(element)) {1736    // Make sure the element is not disabled ...1737    focusable = !element.disabled &&1738        // ... and if a tab index is specified, it allows focus.1739        (!goog.dom.hasSpecifiedTabIndex_(element) ||1740         goog.dom.isTabIndexFocusable_(element));1741  } else {1742    focusable = goog.dom.isFocusableTabIndex(element);1743  }17441745  // IE requires elements to be visible in order to focus them.1746  return focusable && goog.userAgent.IE ?1747             goog.dom.hasNonZeroBoundingRect_(element) : focusable;1748};174917501751/**1752 * Returns true if the element has a specified tab index.1753 * @param {Element} element Element to check.1754 * @return {boolean} Whether the element has a specified tab index.1755 * @private1756 */1757goog.dom.hasSpecifiedTabIndex_ = function(element) {1758  // IE returns 0 for an unset tabIndex, so we must use getAttributeNode(),1759  // which returns an object with a 'specified' property if tabIndex is1760  // specified.  This works on other browsers, too.1761  var attrNode = element.getAttributeNode('tabindex'); // Must be lowercase!1762  return goog.isDefAndNotNull(attrNode) && attrNode.specified;1763};176417651766/**1767 * Returns true if the element's tab index allows the element to be focused.1768 * @param {Element} element Element to check.1769 * @return {boolean} Whether the element's tab index allows focus.1770 * @private1771 */1772goog.dom.isTabIndexFocusable_ = function(element) {1773  var index = element.tabIndex;1774  // NOTE: IE9 puts tabIndex in 16-bit int, e.g. -2 is 65534.1775  return goog.isNumber(index) && index >= 0 && index < 32768;1776};177717781779/**1780 * Returns true if the element is focusable even when tabIndex is not set.1781 * @param {Element} element Element to check.1782 * @return {boolean} Whether the element natively supports focus.1783 * @private1784 */1785goog.dom.nativelySupportsFocus_ = function(element) {1786  return element.tagName == goog.dom.TagName.A ||1787         element.tagName == goog.dom.TagName.INPUT ||1788         element.tagName == goog.dom.TagName.TEXTAREA ||1789         element.tagName == goog.dom.TagName.SELECT ||1790         element.tagName == goog.dom.TagName.BUTTON;1791};179217931794/**1795 * Returns true if the element has a bounding rectangle that would be visible1796 * (i.e. its width and height are greater than zero).1797 * @param {Element} element Element to check.1798 * @return {boolean} Whether the element has a non-zero bounding rectangle.1799 * @private1800 */1801goog.dom.hasNonZeroBoundingRect_ = function(element) {1802  var rect = goog.isFunction(element['getBoundingClientRect']) ?1803      element.getBoundingClientRect() :1804      {'height': element.offsetHeight, 'width': element.offsetWidth};1805  return goog.isDefAndNotNull(rect) && rect.height > 0 && rect.width > 0;1806};180718081809/**1810 * Returns the text content of the current node, without markup and invisible1811 * symbols. New lines are stripped and whitespace is collapsed,1812 * such that each character would be visible.1813 *1814 * In browsers that support it, innerText is used.  Other browsers attempt to1815 * simulate it via node traversal.  Line breaks are canonicalized in IE.1816 *1817 * @param {Node} node The node from which we are getting content.1818 * @return {string} The text content.1819 */1820goog.dom.getTextContent = function(node) {1821  var textContent;1822  // Note(arv): IE9, Opera, and Safari 3 support innerText but they include1823  // text nodes in script tags. So we revert to use a user agent test here.1824  if (goog.dom.BrowserFeature.CAN_USE_INNER_TEXT && ('innerText' in node)) {1825    textContent = goog.string.canonicalizeNewlines(node.innerText);1826    // Unfortunately .innerText() returns text with &shy; symbols1827    // We need to filter it out and then remove duplicate whitespaces1828  } else {1829    var buf = [];1830    goog.dom.getTextContent_(node, buf, true);1831    textContent = buf.join('');1832  }18331834  // Strip &shy; entities. goog.format.insertWordBreaks inserts them in Opera.1835  textContent = textContent.replace(/ \xAD /g, ' ').replace(/\xAD/g, '');1836  // Strip &#8203; entities. goog.format.insertWordBreaks inserts them in IE8.1837  textContent = textContent.replace(/\u200B/g, '');18381839  // Skip this replacement on old browsers with working innerText, which1840  // automatically turns &nbsp; into ' ' and / +/ into ' ' when reading1841  // innerText.1842  if (!goog.dom.BrowserFeature.CAN_USE_INNER_TEXT) {1843    textContent = textContent.replace(/ +/g, ' ');1844  }1845  if (textContent != ' ') {1846    textContent = textContent.replace(/^\s*/, '');1847  }18481849  return textContent;1850};185118521853/**1854 * Returns the text content of the current node, without markup.1855 *1856 * Unlike {@code getTextContent} this method does not collapse whitespaces1857 * or normalize lines breaks.1858 *1859 * @param {Node} node The node from which we are getting content.1860 * @return {string} The raw text content.1861 */1862goog.dom.getRawTextContent = function(node) {1863  var buf = [];1864  goog.dom.getTextContent_(node, buf, false);18651866  return buf.join('');1867};186818691870/**1871 * Recursive support function for text content retrieval.1872 *1873 * @param {Node} node The node from which we are getting content.1874 * @param {Array} buf string buffer.1875 * @param {boolean} normalizeWhitespace Whether to normalize whitespace.1876 * @private1877 */1878goog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) {1879  if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) {1880    // ignore certain tags1881  } else if (node.nodeType == goog.dom.NodeType.TEXT) {1882    if (normalizeWhitespace) {1883      buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, ''));1884    } else {1885      buf.push(node.nodeValue);1886    }1887  } else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {1888    buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]);1889  } else {1890    var child = node.firstChild;1891    while (child) {1892      goog.dom.getTextContent_(child, buf, normalizeWhitespace);1893      child = child.nextSibling;1894    }1895  }1896};189718981899/**1900 * Returns the text length of the text contained in a node, without markup. This1901 * is equivalent to the selection length if the node was selected, or the number1902 * of cursor movements to traverse the node. Images & BRs take one space.  New1903 * lines are ignored.1904 *1905 * @param {Node} node The node whose text content length is being calculated.1906 * @return {number} The length of {@code node}'s text content.1907 */1908goog.dom.getNodeTextLength = function(node) {1909  return goog.dom.getTextContent(node).length;1910};191119121913/**1914 * Returns the text offset of a node relative to one of its ancestors. The text1915 * length is the same as the length calculated by goog.dom.getNodeTextLength.1916 *1917 * @param {Node} node The node whose offset is being calculated.1918 * @param {Node=} opt_offsetParent The node relative to which the offset will1919 *     be calculated. Defaults to the node's owner document's body.1920 * @return {number} The text offset.1921 */1922goog.dom.getNodeTextOffset = function(node, opt_offsetParent) {1923  var root = opt_offsetParent || goog.dom.getOwnerDocument(node).body;1924  var buf = [];1925  while (node && node != root) {1926    var cur = node;1927    while ((cur = cur.previousSibling)) {1928      buf.unshift(goog.dom.getTextContent(cur));1929    }1930    node = node.parentNode;1931  }1932  // Trim left to deal with FF cases when there might be line breaks and empty1933  // nodes at the front of the text1934  return goog.string.trimLeft(buf.join('')).replace(/ +/g, ' ').length;1935};193619371938/**1939 * Returns the node at a given offset in a parent node.  If an object is1940 * provided for the optional third parameter, the node and the remainder of the1941 * offset will stored as properties of this object.1942 * @param {Node} parent The parent node.1943 * @param {number} offset The offset into the parent node.1944 * @param {Object=} opt_result Object to be used to store the return value. The1945 *     return value will be stored in the form {node: Node, remainder: number}1946 *     if this object is provided.1947 * @return {Node} The node at the given offset.1948 */1949goog.dom.getNodeAtOffset = function(parent, offset, opt_result) {1950  var stack = [parent], pos = 0, cur = null;1951  while (stack.length > 0 && pos < offset) {1952    cur = stack.pop();1953    if (cur.nodeName in goog.dom.TAGS_TO_IGNORE_) {1954      // ignore certain tags1955    } else if (cur.nodeType == goog.dom.NodeType.TEXT) {1956      var text = cur.nodeValue.replace(/(\r\n|\r|\n)/g, '').replace(/ +/g, ' ');1957      pos += text.length;1958    } else if (cur.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {1959      pos += goog.dom.PREDEFINED_TAG_VALUES_[cur.nodeName].length;1960    } else {1961      for (var i = cur.childNodes.length - 1; i >= 0; i--) {1962        stack.push(cur.childNodes[i]);1963      }1964    }1965  }1966  if (goog.isObject(opt_result)) {1967    opt_result.remainder = cur ? cur.nodeValue.length + offset - pos - 1 : 0;1968    opt_result.node = cur;1969  }19701971  return cur;1972};197319741975/**1976 * Returns true if the object is a {@code NodeList}.  To qualify as a NodeList,1977 * the object must have a numeric length property and an item function (which1978 * has type 'string' on IE for some reason).1979 * @param {Object} val Object to test.1980 * @return {boolean} Whether the object is a NodeList.1981 */1982goog.dom.isNodeList = function(val) {1983  // TODO(attila): Now the isNodeList is part of goog.dom we can use1984  // goog.userAgent to make this simpler.1985  // A NodeList must have a length property of type 'number' on all platforms.1986  if (val && typeof val.length == 'number') {1987    // A NodeList is an object everywhere except Safari, where it's a function.1988    if (goog.isObject(val)) {1989      // A NodeList must have an item function (on non-IE platforms) or an item1990      // property of type 'string' (on IE).1991      return typeof val.item == 'function' || typeof val.item == 'string';1992    } else if (goog.isFunction(val)) {1993      // On Safari, a NodeList is a function with an item property that is also1994      // a function.1995      return typeof val.item == 'function';1996    }1997  }19981999  // Not a NodeList.2000  return false;2001};200220032004/**2005 * Walks up the DOM hierarchy returning the first ancestor that has the passed2006 * tag name and/or class name. If the passed element matches the specified2007 * criteria, the element itself is returned.2008 * @param {Node} element The DOM node to start with.2009 * @param {?(goog.dom.TagName|string)=} opt_tag The tag name to match (or2010 *     null/undefined to match only based on class name).2011 * @param {?string=} opt_class The class name to match (or null/undefined to2012 *     match only based on tag name).2013 * @return {Element} The first ancestor that matches the passed criteria, or2014 *     null if no match is found.2015 */2016goog.dom.getAncestorByTagNameAndClass = function(element, opt_tag, opt_class) {2017  if (!opt_tag && !opt_class) {2018    return null;2019  }2020  var tagName = opt_tag ? opt_tag.toUpperCase() : null;2021  return /** @type {Element} */ (goog.dom.getAncestor(element,2022      function(node) {2023        return (!tagName || node.nodeName == tagName) &&2024               (!opt_class || goog.isString(node.className) &&2025                   goog.array.contains(node.className.split(/\s+/), opt_class));2026      }, true));2027};202820292030/**2031 * Walks up the DOM hierarchy returning the first ancestor that has the passed2032 * class name. If the passed element matches the specified criteria, the2033 * element itself is returned.2034 * @param {Node} element The DOM node to start with.2035 * @param {string} className The class name to match.2036 * @return {Element} The first ancestor that matches the passed criteria, or2037 *     null if none match.2038 */2039goog.dom.getAncestorByClass = function(element, className) {2040  return goog.dom.getAncestorByTagNameAndClass(element, null, className);2041};204220432044/**2045 * Walks up the DOM hierarchy returning the first ancestor that passes the2046 * matcher function.2047 * @param {Node} element The DOM node to start with.2048 * @param {function(Node) : boolean} matcher A function that returns true if the2049 *     passed node matches the desired criteria.2050 * @param {boolean=} opt_includeNode If true, the node itself is included in2051 *     the search (the first call to the matcher will pass startElement as2052 *     the node to test).2053 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the2054 *     dom.2055 * @return {Node} DOM node that matched the matcher, or null if there was2056 *     no match.2057 */2058goog.dom.getAncestor = function(2059    element, matcher, opt_includeNode, opt_maxSearchSteps) {2060  if (!opt_includeNode) {2061    element = element.parentNode;2062  }2063  var ignoreSearchSteps = opt_maxSearchSteps == null;2064  var steps = 0;2065  while (element && (ignoreSearchSteps || steps <= opt_maxSearchSteps)) {2066    if (matcher(element)) {2067      return element;2068    }2069    element = element.parentNode;2070    steps++;2071  }2072  // Reached the root of the DOM without a match2073  return null;2074};207520762077/**2078 * Determines the active element in the given document.2079 * @param {Document} doc The document to look in.2080 * @return {Element} The active element.2081 */2082goog.dom.getActiveElement = function(doc) {2083  try {2084    return doc && doc.activeElement;2085  } catch (e) {2086    // NOTE(nicksantos): Sometimes, evaluating document.activeElement in IE2087    // throws an exception. I'm not 100% sure why, but I suspect it chokes2088    // on document.activeElement if the activeElement has been recently2089    // removed from the DOM by a JS operation.2090    //2091    // We assume that an exception here simply means2092    // "there is no active element."2093  }20942095  return null;2096};209720982099/**2100 * Gives the current devicePixelRatio.2101 *2102 * By default, this is the value of window.devicePixelRatio (which should be2103 * preferred if present).2104 *2105 * If window.devicePixelRatio is not present, the ratio is calculated with2106 * window.matchMedia, if present. Otherwise, gives 1.0.2107 *2108 * Some browsers (including Chrome) consider the browser zoom level in the pixel2109 * ratio, so the value may change across multiple calls.2110 *2111 * @return {number} The number of actual pixels per virtual pixel.2112 */2113goog.dom.getPixelRatio = function() {2114  var win = goog.dom.getWindow();21152116  // devicePixelRatio does not work on Mobile firefox.2117  // TODO(user): Enable this check on a known working mobile Gecko version.2118  // Filed a bug: https://bugzilla.mozilla.org/show_bug.cgi?id=8968042119  var isFirefoxMobile = goog.userAgent.GECKO && goog.userAgent.MOBILE;21202121  if (goog.isDef(win.devicePixelRatio) && !isFirefoxMobile) {2122    return win.devicePixelRatio;2123  } else if (win.matchMedia) {2124    return goog.dom.matchesPixelRatio_(.75) ||2125           goog.dom.matchesPixelRatio_(1.5) ||2126           goog.dom.matchesPixelRatio_(2) ||2127           goog.dom.matchesPixelRatio_(3) || 1;2128  }2129  return 1;2130};213121322133/**2134 * Calculates a mediaQuery to check if the current device supports the2135 * given actual to virtual pixel ratio.2136 * @param {number} pixelRatio The ratio of actual pixels to virtual pixels.2137 * @return {number} pixelRatio if applicable, otherwise 0.2138 * @private2139 */2140goog.dom.matchesPixelRatio_ = function(pixelRatio) {2141  var win = goog.dom.getWindow();2142  var query = ('(-webkit-min-device-pixel-ratio: ' + pixelRatio + '),' +2143               '(min--moz-device-pixel-ratio: ' + pixelRatio + '),' +2144               '(min-resolution: ' + pixelRatio + 'dppx)');2145  return win.matchMedia(query).matches ? pixelRatio : 0;2146};2147214821492150/**2151 * Create an instance of a DOM helper with a new document object.2152 * @param {Document=} opt_document Document object to associate with this2153 *     DOM helper.2154 * @constructor2155 */2156goog.dom.DomHelper = function(opt_document) {2157  /**2158   * Reference to the document object to use2159   * @type {!Document}2160   * @private2161   */2162  this.document_ = opt_document || goog.global.document || document;2163};216421652166/**2167 * Gets the dom helper object for the document where the element resides.2168 * @param {Node=} opt_node If present, gets the DomHelper for this node.2169 * @return {!goog.dom.DomHelper} The DomHelper.2170 */2171goog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper;217221732174/**2175 * Sets the document object.2176 * @param {!Document} document Document object.2177 */2178goog.dom.DomHelper.prototype.setDocument = function(document) {2179  this.document_ = document;2180};218121822183/**2184 * Gets the document object being used by the dom library.2185 * @return {!Document} Document object.2186 */2187goog.dom.DomHelper.prototype.getDocument = function() {2188  return this.document_;2189};219021912192/**2193 * Alias for {@code getElementById}. If a DOM node is passed in then we just2194 * return that.2195 * @param {string|Element} element Element ID or a DOM node.2196 * @return {Element} The element with the given ID, or the node passed in.2197 */2198goog.dom.DomHelper.prototype.getElement = function(element) {2199  return goog.dom.getElementHelper_(this.document_, element);2200};220122022203/**2204 * Gets an element by id, asserting that the element is found.2205 *2206 * This is used when an element is expected to exist, and should fail with2207 * an assertion error if it does not (if assertions are enabled).2208 *2209 * @param {string} id Element ID.2210 * @return {!Element} The element with the given ID, if it exists.2211 */2212goog.dom.DomHelper.prototype.getRequiredElement = function(id) {2213  return goog.dom.getRequiredElementHelper_(this.document_, id);2214};221522162217/**2218 * Alias for {@code getElement}.2219 * @param {string|Element} element Element ID or a DOM node.2220 * @return {Element} The element with the given ID, or the node passed in.2221 * @deprecated Use {@link goog.dom.DomHelper.prototype.getElement} instead.2222 */2223goog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement;222422252226/**2227 * Looks up elements by both tag and class name, using browser native functions2228 * ({@code querySelectorAll}, {@code getElementsByTagName} or2229 * {@code getElementsByClassName}) where possible. The returned array is a live2230 * NodeList or a static list depending on the code path taken.2231 *2232 * @see goog.dom.query2233 *2234 * @param {?string=} opt_tag Element tag name or * for all tags.2235 * @param {?string=} opt_class Optional class name.2236 * @param {(Document|Element)=} opt_el Optional element to look in.2237 * @return { {length: number} } Array-like list of elements (only a length2238 *     property and numerical indices are guaranteed to exist).2239 */2240goog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(opt_tag,2241                                                                     opt_class,2242                                                                     opt_el) {2243  return goog.dom.getElementsByTagNameAndClass_(this.document_, opt_tag,2244                                                opt_class, opt_el);2245};224622472248/**2249 * Returns an array of all the elements with the provided className.2250 * @see {goog.dom.query}2251 * @param {string} className the name of the class to look for.2252 * @param {Element|Document=} opt_el Optional element to look in.2253 * @return { {length: number} } The items found with the class name provided.2254 */2255goog.dom.DomHelper.prototype.getElementsByClass = function(className, opt_el) {2256  var doc = opt_el || this.document_;2257  return goog.dom.getElementsByClass(className, doc);2258};225922602261/**2262 * Returns the first element we find matching the provided class name.2263 * @see {goog.dom.query}2264 * @param {string} className the name of the class to look for.2265 * @param {(Element|Document)=} opt_el Optional element to look in.2266 * @return {Element} The first item found with the class name provided.2267 */2268goog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) {2269  var doc = opt_el || this.document_;2270  return goog.dom.getElementByClass(className, doc);2271};227222732274/**2275 * Ensures an element with the given className exists, and then returns the2276 * first element with the provided className.2277 * @see {goog.dom.query}2278 * @param {string} className the name of the class to look for.2279 * @param {(!Element|!Document)=} opt_root Optional element or document to look2280 *     in.2281 * @return {!Element} The first item found with the class name provided.2282 * @throws {goog.asserts.AssertionError} Thrown if no element is found.2283 */2284goog.dom.DomHelper.prototype.getRequiredElementByClass = function(className,2285                                                                  opt_root) {2286  var root = opt_root || this.document_;2287  return goog.dom.getRequiredElementByClass(className, root);2288};228922902291/**2292 * Alias for {@code getElementsByTagNameAndClass}.2293 * @deprecated Use DomHelper getElementsByTagNameAndClass.2294 * @see goog.dom.query2295 *2296 * @param {?string=} opt_tag Element tag name.2297 * @param {?string=} opt_class Optional class name.2298 * @param {Element=} opt_el Optional element to look in.2299 * @return { {length: number} } Array-like list of elements (only a length2300 *     property and numerical indices are guaranteed to exist).2301 */2302goog.dom.DomHelper.prototype.$$ =2303    goog.dom.DomHelper.prototype.getElementsByTagNameAndClass;230423052306/**2307 * Sets a number of properties on a node.2308 * @param {Element} element DOM node to set properties on.2309 * @param {Object} properties Hash of property:value pairs.2310 */2311goog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties;231223132314/**2315 * Gets the dimensions of the viewport.2316 * @param {Window=} opt_window Optional window element to test. Defaults to2317 *     the window of the Dom Helper.2318 * @return {!goog.math.Size} Object with values 'width' and 'height'.2319 */2320goog.dom.DomHelper.prototype.getViewportSize = function(opt_window) {2321  // TODO(arv): This should not take an argument. That breaks the rule of a2322  // a DomHelper representing a single frame/window/document.2323  return goog.dom.getViewportSize(opt_window || this.getWindow());2324};232523262327/**2328 * Calculates the height of the document.2329 *2330 * @return {number} The height of the document.2331 */2332goog.dom.DomHelper.prototype.getDocumentHeight = function() {2333  return goog.dom.getDocumentHeight_(this.getWindow());2334};233523362337/**2338 * Typedef for use with goog.dom.createDom and goog.dom.append.2339 * @typedef {Object|string|Array|NodeList}2340 */2341goog.dom.Appendable;234223432344/**2345 * Returns a dom node with a set of attributes.  This function accepts varargs2346 * for subsequent nodes to be added.  Subsequent nodes will be added to the2347 * first node as childNodes.2348 *2349 * So:2350 * <code>createDom('div', null, createDom('p'), createDom('p'));</code>2351 * would return a div with two child paragraphs2352 *2353 * An easy way to move all child nodes of an existing element to a new parent2354 * element is:2355 * <code>createDom('div', null, oldElement.childNodes);</code>2356 * which will remove all child nodes from the old element and add them as2357 * child nodes of the new DIV.2358 *2359 * @param {string} tagName Tag to create.2360 * @param {Object|string=} opt_attributes If object, then a map of name-value2361 *     pairs for attributes. If a string, then this is the className of the new2362 *     element.2363 * @param {...goog.dom.Appendable} var_args Further DOM nodes or2364 *     strings for text nodes. If one of the var_args is an array or2365 *     NodeList, its elements will be added as childNodes instead.2366 * @return {!Element} Reference to a DOM node.2367 */2368goog.dom.DomHelper.prototype.createDom = function(tagName,2369                                                  opt_attributes,2370                                                  var_args) {2371  return goog.dom.createDom_(this.document_, arguments);2372};237323742375/**2376 * Alias for {@code createDom}.2377 * @param {string} tagName Tag to create.2378 * @param {(Object|string)=} opt_attributes If object, then a map of name-value2379 *     pairs for attributes. If a string, then this is the className of the new2380 *     element.2381 * @param {...goog.dom.Appendable} var_args Further DOM nodes or strings for2382 *     text nodes.  If one of the var_args is an array, its children will be2383 *     added as childNodes instead.2384 * @return {!Element} Reference to a DOM node.2385 * @deprecated Use {@link goog.dom.DomHelper.prototype.createDom} instead.2386 */2387goog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom;238823892390/**2391 * Creates a new element.2392 * @param {string} name Tag name.2393 * @return {!Element} The new element.2394 */2395goog.dom.DomHelper.prototype.createElement = function(name) {2396  return this.document_.createElement(name);2397};239823992400/**2401 * Creates a new text node.2402 * @param {number|string} content Content.2403 * @return {!Text} The new text node.2404 */2405goog.dom.DomHelper.prototype.createTextNode = function(content) {2406  return this.document_.createTextNode(String(content));2407};240824092410/**2411 * Create a table.2412 * @param {number} rows The number of rows in the table.  Must be >= 1.2413 * @param {number} columns The number of columns in the table.  Must be >= 1.2414 * @param {boolean=} opt_fillWithNbsp If true, fills table entries with nsbps.2415 * @return {!Element} The created table.2416 */2417goog.dom.DomHelper.prototype.createTable = function(rows, columns,2418    opt_fillWithNbsp) {2419  return goog.dom.createTable_(this.document_, rows, columns,2420      !!opt_fillWithNbsp);2421};242224232424/**2425 * Converts an HTML string into a node or a document fragment.  A single Node2426 * is used if the {@code htmlString} only generates a single node.  If the2427 * {@code htmlString} generates multiple nodes then these are put inside a2428 * {@code DocumentFragment}.2429 *2430 * @param {string} htmlString The HTML string to convert.2431 * @return {!Node} The resulting node.2432 */2433goog.dom.DomHelper.prototype.htmlToDocumentFragment = function(htmlString) {2434  return goog.dom.htmlToDocumentFragment_(this.document_, htmlString);2435};243624372438/**2439 * Returns true if the browser is in "CSS1-compatible" (standards-compliant)2440 * mode, false otherwise.2441 * @return {boolean} True if in CSS1-compatible mode.2442 */2443goog.dom.DomHelper.prototype.isCss1CompatMode = function() {2444  return goog.dom.isCss1CompatMode_(this.document_);2445};244624472448/**2449 * Gets the window object associated with the document.2450 * @return {!Window} The window associated with the given document.2451 */2452goog.dom.DomHelper.prototype.getWindow = function() {2453  return goog.dom.getWindow_(this.document_);2454};245524562457/**2458 * Gets the document scroll element.2459 * @return {!Element} Scrolling element.2460 */2461goog.dom.DomHelper.prototype.getDocumentScrollElement = function() {2462  return goog.dom.getDocumentScrollElement_(this.document_);2463};246424652466/**2467 * Gets the document scroll distance as a coordinate object.2468 * @return {!goog.math.Coordinate} Object with properties 'x' and 'y'.2469 */2470goog.dom.DomHelper.prototype.getDocumentScroll = function() {2471  return goog.dom.getDocumentScroll_(this.document_);2472};247324742475/**2476 * Determines the active element in the given document.2477 * @param {Document=} opt_doc The document to look in.2478 * @return {Element} The active element.2479 */2480goog.dom.DomHelper.prototype.getActiveElement = function(opt_doc) {2481  return goog.dom.getActiveElement(opt_doc || this.document_);2482};248324842485/**2486 * Appends a child to a node.2487 * @param {Node} parent Parent.2488 * @param {Node} child Child.2489 */2490goog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild;249124922493/**2494 * Appends a node with text or other nodes.2495 * @param {!Node} parent The node to append nodes to.2496 * @param {...goog.dom.Appendable} var_args The things to append to the node.2497 *     If this is a Node it is appended as is.2498 *     If this is a string then a text node is appended.2499 *     If this is an array like object then fields 0 to length - 1 are appended.2500 */2501goog.dom.DomHelper.prototype.append = goog.dom.append;250225032504/**2505 * Determines if the given node can contain children, intended to be used for2506 * HTML generation.2507 *2508 * @param {Node} node The node to check.2509 * @return {boolean} Whether the node can contain children.2510 */2511goog.dom.DomHelper.prototype.canHaveChildren = goog.dom.canHaveChildren;251225132514/**2515 * Removes all the child nodes on a DOM node.2516 * @param {Node} node Node to remove children from.2517 */2518goog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren;251925202521/**2522 * Inserts a new node before an existing reference node (i.e., as the previous2523 * sibling). If the reference node has no parent, then does nothing.2524 * @param {Node} newNode Node to insert.2525 * @param {Node} refNode Reference node to insert before.2526 */2527goog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore;252825292530/**2531 * Inserts a new node after an existing reference node (i.e., as the next2532 * sibling). If the reference node has no parent, then does nothing.2533 * @param {Node} newNode Node to insert.2534 * @param {Node} refNode Reference node to insert after.2535 */2536goog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter;253725382539/**2540 * Insert a child at a given index. If index is larger than the number of child2541 * nodes that the parent currently has, the node is inserted as the last child2542 * node.2543 * @param {Element} parent The element into which to insert the child.2544 * @param {Node} child The element to insert.2545 * @param {number} index The index at which to insert the new child node. Must2546 *     not be negative.2547 */2548goog.dom.DomHelper.prototype.insertChildAt = goog.dom.insertChildAt;254925502551/**2552 * Removes a node from its parent.2553 * @param {Node} node The node to remove.2554 * @return {Node} The node removed if removed; else, null.2555 */2556goog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode;255725582559/**2560 * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no2561 * parent.2562 * @param {Node} newNode Node to insert.2563 * @param {Node} oldNode Node to replace.2564 */2565goog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode;256625672568/**2569 * Flattens an element. That is, removes it and replace it with its children.2570 * @param {Element} element The element to flatten.2571 * @return {Element|undefined} The original element, detached from the document2572 *     tree, sans children, or undefined if the element was already not in the2573 *     document.2574 */2575goog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement;257625772578/**2579 * Returns an array containing just the element children of the given element.2580 * @param {Element} element The element whose element children we want.2581 * @return {!(Array|NodeList)} An array or array-like list of just the element2582 *     children of the given element.2583 */2584goog.dom.DomHelper.prototype.getChildren = goog.dom.getChildren;258525862587/**2588 * Returns the first child node that is an element.2589 * @param {Node} node The node to get the first child element of.2590 * @return {Element} The first child node of {@code node} that is an element.2591 */2592goog.dom.DomHelper.prototype.getFirstElementChild =2593    goog.dom.getFirstElementChild;259425952596/**2597 * Returns the last child node that is an element.2598 * @param {Node} node The node to get the last child element of.2599 * @return {Element} The last child node of {@code node} that is an element.2600 */2601goog.dom.DomHelper.prototype.getLastElementChild = goog.dom.getLastElementChild;260226032604/**2605 * Returns the first next sibling that is an element.2606 * @param {Node} node The node to get the next sibling element of.2607 * @return {Element} The next sibling of {@code node} that is an element.2608 */2609goog.dom.DomHelper.prototype.getNextElementSibling =2610    goog.dom.getNextElementSibling;261126122613/**2614 * Returns the first previous sibling that is an element.2615 * @param {Node} node The node to get the previous sibling element of.2616 * @return {Element} The first previous sibling of {@code node} that is2617 *     an element.2618 */2619goog.dom.DomHelper.prototype.getPreviousElementSibling =2620    goog.dom.getPreviousElementSibling;262126222623/**2624 * Returns the next node in source order from the given node.2625 * @param {Node} node The node.2626 * @return {Node} The next node in the DOM tree, or null if this was the last2627 *     node.2628 */2629goog.dom.DomHelper.prototype.getNextNode = goog.dom.getNextNode;263026312632/**2633 * Returns the previous node in source order from the given node.2634 * @param {Node} node The node.2635 * @return {Node} The previous node in the DOM tree, or null if this was the2636 *     first node.2637 */2638goog.dom.DomHelper.prototype.getPreviousNode = goog.dom.getPreviousNode;263926402641/**2642 * Whether the object looks like a DOM node.2643 * @param {?} obj The object being tested for node likeness.2644 * @return {boolean} Whether the object looks like a DOM node.2645 */2646goog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike;264726482649/**2650 * Whether the object looks like an Element.2651 * @param {?} obj The object being tested for Element likeness.2652 * @return {boolean} Whether the object looks like an Element.2653 */2654goog.dom.DomHelper.prototype.isElement = goog.dom.isElement;265526562657/**2658 * Returns true if the specified value is a Window object. This includes the2659 * global window for HTML pages, and iframe windows.2660 * @param {?} obj Variable to test.2661 * @return {boolean} Whether the variable is a window.2662 */2663goog.dom.DomHelper.prototype.isWindow = goog.dom.isWindow;266426652666/**2667 * Returns an element's parent, if it's an Element.2668 * @param {Element} element The DOM element.2669 * @return {Element} The parent, or null if not an Element.2670 */2671goog.dom.DomHelper.prototype.getParentElement = goog.dom.getParentElement;267226732674/**2675 * Whether a node contains another node.2676 * @param {Node} parent The node that should contain the other node.2677 * @param {Node} descendant The node to test presence of.2678 * @return {boolean} Whether the parent node contains the descendent node.2679 */2680goog.dom.DomHelper.prototype.contains = goog.dom.contains;268126822683/**2684 * Compares the document order of two nodes, returning 0 if they are the same2685 * node, a negative number if node1 is before node2, and a positive number if2686 * node2 is before node1.  Note that we compare the order the tags appear in the2687 * document so in the tree <b><i>text</i></b> the B node is considered to be2688 * before the I node.2689 *2690 * @param {Node} node1 The first node to compare.2691 * @param {Node} node2 The second node to compare.2692 * @return {number} 0 if the nodes are the same node, a negative number if node12693 *     is before node2, and a positive number if node2 is before node1.2694 */2695goog.dom.DomHelper.prototype.compareNodeOrder = goog.dom.compareNodeOrder;269626972698/**2699 * Find the deepest common ancestor of the given nodes.2700 * @param {...Node} var_args The nodes to find a common ancestor of.2701 * @return {Node} The common ancestor of the nodes, or null if there is none.2702 *     null will only be returned if two or more of the nodes are from different2703 *     documents.2704 */2705goog.dom.DomHelper.prototype.findCommonAncestor = goog.dom.findCommonAncestor;270627072708/**2709 * Returns the owner document for a node.2710 * @param {Node} node The node to get the document for.2711 * @return {!Document} The document owning the node.2712 */2713goog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument;271427152716/**2717 * Cross browser function for getting the document element of an iframe.2718 * @param {Element} iframe Iframe element.2719 * @return {!Document} The frame content document.2720 */2721goog.dom.DomHelper.prototype.getFrameContentDocument =2722    goog.dom.getFrameContentDocument;272327242725/**2726 * Cross browser function for getting the window of a frame or iframe.2727 * @param {Element} frame Frame element.2728 * @return {Window} The window associated with the given frame.2729 */2730goog.dom.DomHelper.prototype.getFrameContentWindow =2731    goog.dom.getFrameContentWindow;273227332734/**2735 * Sets the text content of a node, with cross-browser support.2736 * @param {Node} node The node to change the text content of.2737 * @param {string|number} text The value that should replace the node's content.2738 */2739goog.dom.DomHelper.prototype.setTextContent = goog.dom.setTextContent;274027412742/**2743 * Gets the outerHTML of a node, which islike innerHTML, except that it2744 * actually contains the HTML of the node itself.2745 * @param {Element} element The element to get the HTML of.2746 * @return {string} The outerHTML of the given element.2747 */2748goog.dom.DomHelper.prototype.getOuterHtml = goog.dom.getOuterHtml;274927502751/**2752 * Finds the first descendant node that matches the filter function. This does2753 * a depth first search.2754 * @param {Node} root The root of the tree to search.2755 * @param {function(Node) : boolean} p The filter function.2756 * @return {Node|undefined} The found node or undefined if none is found.2757 */2758goog.dom.DomHelper.prototype.findNode = goog.dom.findNode;275927602761/**2762 * Finds all the descendant nodes that matches the filter function. This does a2763 * depth first search.2764 * @param {Node} root The root of the tree to search.2765 * @param {function(Node) : boolean} p The filter function.2766 * @return {Array.<Node>} The found nodes or an empty array if none are found.2767 */2768goog.dom.DomHelper.prototype.findNodes = goog.dom.findNodes;276927702771/**2772 * Returns true if the element has a tab index that allows it to receive2773 * keyboard focus (tabIndex >= 0), false otherwise.  Note that some elements2774 * natively support keyboard focus, even if they have no tab index.2775 * @param {Element} element Element to check.2776 * @return {boolean} Whether the element has a tab index that allows keyboard2777 *     focus.2778 */2779goog.dom.DomHelper.prototype.isFocusableTabIndex = goog.dom.isFocusableTabIndex;278027812782/**2783 * Enables or disables keyboard focus support on the element via its tab index.2784 * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true2785 * (or elements that natively support keyboard focus, like form elements) can2786 * receive keyboard focus.  See http://go/tabindex for more info.2787 * @param {Element} element Element whose tab index is to be changed.2788 * @param {boolean} enable Whether to set or remove a tab index on the element2789 *     that supports keyboard focus.2790 */2791goog.dom.DomHelper.prototype.setFocusableTabIndex =2792    goog.dom.setFocusableTabIndex;279327942795/**2796 * Returns true if the element can be focused, i.e. it has a tab index that2797 * allows it to receive keyboard focus (tabIndex >= 0), or it is an element2798 * that natively supports keyboard focus.2799 * @param {Element} element Element to check.2800 * @return {boolean} Whether the element allows keyboard focus.2801 */2802goog.dom.DomHelper.prototype.isFocusable = goog.dom.isFocusable;280328042805/**2806 * Returns the text contents of the current node, without markup. New lines are2807 * stripped and whitespace is collapsed, such that each character would be2808 * visible.2809 *2810 * In browsers that support it, innerText is used.  Other browsers attempt to2811 * simulate it via node traversal.  Line breaks are canonicalized in IE.2812 *2813 * @param {Node} node The node from which we are getting content.2814 * @return {string} The text content.2815 */2816goog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent;281728182819/**2820 * Returns the text length of the text contained in a node, without markup. This2821 * is equivalent to the selection length if the node was selected, or the number2822 * of cursor movements to traverse the node. Images & BRs take one space.  New2823 * lines are ignored.2824 *2825 * @param {Node} node The node whose text content length is being calculated.2826 * @return {number} The length of {@code node}'s text content.2827 */2828goog.dom.DomHelper.prototype.getNodeTextLength = goog.dom.getNodeTextLength;282928302831/**2832 * Returns the text offset of a node relative to one of its ancestors. The text2833 * length is the same as the length calculated by2834 * {@code goog.dom.getNodeTextLength}.2835 *2836 * @param {Node} node The node whose offset is being calculated.2837 * @param {Node=} opt_offsetParent Defaults to the node's owner document's body.2838 * @return {number} The text offset.2839 */2840goog.dom.DomHelper.prototype.getNodeTextOffset = goog.dom.getNodeTextOffset;284128422843/**2844 * Returns the node at a given offset in a parent node.  If an object is2845 * provided for the optional third parameter, the node and the remainder of the2846 * offset will stored as properties of this object.2847 * @param {Node} parent The parent node.2848 * @param {number} offset The offset into the parent node.2849 * @param {Object=} opt_result Object to be used to store the return value. The2850 *     return value will be stored in the form {node: Node, remainder: number}2851 *     if this object is provided.2852 * @return {Node} The node at the given offset.2853 */2854goog.dom.DomHelper.prototype.getNodeAtOffset = goog.dom.getNodeAtOffset;285528562857/**2858 * Returns true if the object is a {@code NodeList}.  To qualify as a NodeList,2859 * the object must have a numeric length property and an item function (which2860 * has type 'string' on IE for some reason).2861 * @param {Object} val Object to test.2862 * @return {boolean} Whether the object is a NodeList.2863 */2864goog.dom.DomHelper.prototype.isNodeList = goog.dom.isNodeList;286528662867/**2868 * Walks up the DOM hierarchy returning the first ancestor that has the passed2869 * tag name and/or class name. If the passed element matches the specified2870 * criteria, the element itself is returned.2871 * @param {Node} element The DOM node to start with.2872 * @param {?(goog.dom.TagName|string)=} opt_tag The tag name to match (or2873 *     null/undefined to match only based on class name).2874 * @param {?string=} opt_class The class name to match (or null/undefined to2875 *     match only based on tag name).2876 * @return {Element} The first ancestor that matches the passed criteria, or2877 *     null if no match is found.2878 */2879goog.dom.DomHelper.prototype.getAncestorByTagNameAndClass =2880    goog.dom.getAncestorByTagNameAndClass;288128822883/**2884 * Walks up the DOM hierarchy returning the first ancestor that has the passed2885 * class name. If the passed element matches the specified criteria, the2886 * element itself is returned.2887 * @param {Node} element The DOM node to start with.2888 * @param {string} class The class name to match.2889 * @return {Element} The first ancestor that matches the passed criteria, or2890 *     null if none match.2891 */2892goog.dom.DomHelper.prototype.getAncestorByClass =2893    goog.dom.getAncestorByClass;289428952896/**2897 * Walks up the DOM hierarchy returning the first ancestor that passes the2898 * matcher function.2899 * @param {Node} element The DOM node to start with.2900 * @param {function(Node) : boolean} matcher A function that returns true if the2901 *     passed node matches the desired criteria.2902 * @param {boolean=} opt_includeNode If true, the node itself is included in2903 *     the search (the first call to the matcher will pass startElement as2904 *     the node to test).2905 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the2906 *     dom.2907 * @return {Node} DOM node that matched the matcher, or null if there was2908 *     no match.2909 */2910goog.dom.DomHelper.prototype.getAncestor = goog.dom.getAncestor;