Path: blob/trunk/third_party/closure/goog/dom/dom.js
4184 views
/**1* @license2* Copyright The Closure Library Authors.3* SPDX-License-Identifier: Apache-2.04*/56/**7* @fileoverview Utilities for manipulating the browser's Document Object Model8* Inspiration taken *heavily* from mochikit (http://mochikit.com/).9*10* You can use {@link goog.dom.DomHelper} to create new dom helpers that refer11* to a different document object. This is useful if you are working with12* frames or multiple windows.13*14* @suppress {strictMissingProperties}15*/161718// TODO(arv): Rename/refactor getTextContent and getRawTextContent. The problem19// is that getTextContent should mimic the DOM3 textContent. We should add a20// getInnerText (or getText) which tries to return the visible text, innerText.212223goog.provide('goog.dom');24goog.provide('goog.dom.Appendable');25goog.provide('goog.dom.DomHelper');2627goog.require('goog.array');28goog.require('goog.asserts');29goog.require('goog.asserts.dom');30goog.require('goog.dom.BrowserFeature');31goog.require('goog.dom.NodeType');32goog.require('goog.dom.TagName');33goog.require('goog.dom.safe');34goog.require('goog.html.SafeHtml');35goog.require('goog.html.uncheckedconversions');36goog.require('goog.math.Coordinate');37goog.require('goog.math.Size');38goog.require('goog.object');39goog.require('goog.string');40goog.require('goog.string.Const');41goog.require('goog.string.Unicode');42goog.require('goog.userAgent');4344goog.require('goog.utils');454647/**48* @define {boolean} Whether we know at compile time that the browser is in49* quirks mode.50*/51goog.dom.ASSUME_QUIRKS_MODE = goog.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.dom.ASSUME_STANDARDS_MODE =59goog.define('goog.dom.ASSUME_STANDARDS_MODE', false);606162/**63* Whether we know the compatibility mode at compile time.64* @type {boolean}65* @private66*/67goog.dom.COMPAT_MODE_KNOWN_ =68goog.dom.ASSUME_QUIRKS_MODE || goog.dom.ASSUME_STANDARDS_MODE;697071/**72* Gets the DomHelper object for the document where the element resides.73* @param {(Node|Window)=} opt_element If present, gets the DomHelper for this74* element.75* @return {!goog.dom.DomHelper} The DomHelper.76*/77goog.dom.getDomHelper = function(opt_element) {78'use strict';79return opt_element ?80new goog.dom.DomHelper(goog.dom.getOwnerDocument(opt_element)) :81(goog.dom.defaultDomHelper_ ||82(goog.dom.defaultDomHelper_ = new goog.dom.DomHelper()));83};848586/**87* Cached default DOM helper.88* @type {!goog.dom.DomHelper|undefined}89* @private90*/91goog.dom.defaultDomHelper_;929394/**95* Gets the document object being used by the dom library.96* @return {!Document} Document object.97*/98goog.dom.getDocument = function() {99'use strict';100return document;101};102103104/**105* Gets an element from the current document by element id.106*107* If an Element is passed in, it is returned.108*109* @param {string|Element} element Element ID or a DOM node.110* @return {Element} The element with the given ID, or the node passed in.111*/112goog.dom.getElement = function(element) {113'use strict';114return goog.dom.getElementHelper_(document, element);115};116117118/**119* Gets an HTML element from the current document by element id.120*121* @param {string} id122* @return {?HTMLElement} The element with the given ID or null if no such123* element exists.124*/125goog.dom.getHTMLElement = function(id) {126'use strict'127const element = goog.dom.getElement(id);128if (!element) {129return null;130}131return goog.asserts.dom.assertIsHtmlElement(element);132};133134135/**136* Gets an element by id from the given document (if present).137* If an element is given, it is returned.138* @param {!Document} doc139* @param {string|Element} element Element ID or a DOM node.140* @return {Element} The resulting element.141* @private142*/143goog.dom.getElementHelper_ = function(doc, element) {144'use strict';145return typeof element === 'string' ? doc.getElementById(element) : element;146};147148149/**150* Gets an element by id, asserting that the element is found.151*152* This is used when an element is expected to exist, and should fail with153* an assertion error if it does not (if assertions are enabled).154*155* @param {string} id Element ID.156* @return {!Element} The element with the given ID, if it exists.157*/158goog.dom.getRequiredElement = function(id) {159'use strict';160return goog.dom.getRequiredElementHelper_(document, id);161};162163164/**165* Gets an HTML element by id, asserting that the element is found.166*167* This is used when an element is expected to exist, and should fail with168* an assertion error if it does not (if assertions are enabled).169*170* @param {string} id Element ID.171* @return {!HTMLElement} The element with the given ID, if it exists.172*/173goog.dom.getRequiredHTMLElement = function(id) {174'use strict'175return goog.asserts.dom.assertIsHtmlElement(176goog.dom.getRequiredElementHelper_(document, id));177};178179180/**181* Helper function for getRequiredElementHelper functions, both static and182* on DomHelper. Asserts the element with the given id exists.183* @param {!Document} doc184* @param {string} id185* @return {!Element} The element with the given ID, if it exists.186* @private187*/188goog.dom.getRequiredElementHelper_ = function(doc, id) {189'use strict';190// To prevent users passing in Elements as is permitted in getElement().191goog.asserts.assertString(id);192var element = goog.dom.getElementHelper_(doc, id);193return goog.asserts.assert(element, 'No element found with id: ' + id);194};195196197/**198* Alias for getElement.199* @param {string|Element} element Element ID or a DOM node.200* @return {Element} The element with the given ID, or the node passed in.201* @deprecated Use {@link goog.dom.getElement} instead.202*/203goog.dom.$ = goog.dom.getElement;204205206/**207* Gets elements by tag name.208* @param {!goog.dom.TagName<T>} tagName209* @param {(!Document|!Element)=} opt_parent Parent element or document where to210* look for elements. Defaults to document.211* @return {!NodeList<R>} List of elements. The members of the list are212* {!Element} if tagName is not a member of goog.dom.TagName or more213* specific types if it is (e.g. {!HTMLAnchorElement} for214* goog.dom.TagName.A).215* @template T216* @template R := cond(isUnknown(T), 'Element', T) =:217*/218goog.dom.getElementsByTagName = function(tagName, opt_parent) {219'use strict';220var parent = opt_parent || document;221return parent.getElementsByTagName(String(tagName));222};223224225/**226* Looks up elements by both tag and class name, using browser native functions227* (`querySelectorAll`, `getElementsByTagName` or228* `getElementsByClassName`) where possible. This function229* is a useful, if limited, way of collecting a list of DOM elements230* with certain characteristics. `querySelectorAll` offers a231* more powerful and general solution which allows matching on CSS3232* selector expressions.233*234* Note that tag names are case sensitive in the SVG namespace, and this235* function converts opt_tag to uppercase for comparisons. For queries in the236* SVG namespace you should use querySelector or querySelectorAll instead.237* https://bugzilla.mozilla.org/show_bug.cgi?id=963870238* https://bugs.webkit.org/show_bug.cgi?id=83438239*240* @see {https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelectorAll}241*242* @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.243* @param {?string=} opt_class Optional class name.244* @param {(Document|Element)=} opt_el Optional element to look in.245* @return {!IArrayLike<R>} Array-like list of elements (only a length property246* and numerical indices are guaranteed to exist). The members of the array247* are {!Element} if opt_tag is not a member of goog.dom.TagName or more248* specific types if it is (e.g. {!HTMLAnchorElement} for249* goog.dom.TagName.A).250* @template T251* @template R := cond(isUnknown(T), 'Element', T) =:252*/253goog.dom.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) {254'use strict';255return goog.dom.getElementsByTagNameAndClass_(256document, opt_tag, opt_class, opt_el);257};258259260/**261* Gets the first element matching the tag and the class.262*263* @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.264* @param {?string=} opt_class Optional class name.265* @param {(Document|Element)=} opt_el Optional element to look in.266* @return {?R} Reference to a DOM node. The return type is {?Element} if267* tagName is a string or a more specific type if it is a member of268* goog.dom.TagName (e.g. {?HTMLAnchorElement} for goog.dom.TagName.A).269* @template T270* @template R := cond(isUnknown(T), 'Element', T) =:271*/272goog.dom.getElementByTagNameAndClass = function(opt_tag, opt_class, opt_el) {273'use strict';274return goog.dom.getElementByTagNameAndClass_(275document, opt_tag, opt_class, opt_el);276};277278279/**280* Returns a static, array-like list of the elements with the provided281* className.282*283* @param {string} className the name of the class to look for.284* @param {(Document|Element)=} opt_el Optional element to look in.285* @return {!IArrayLike<!Element>} The items found with the class name provided.286*/287goog.dom.getElementsByClass = function(className, opt_el) {288'use strict';289var parent = opt_el || document;290if (goog.dom.canUseQuerySelector_(parent)) {291return parent.querySelectorAll('.' + className);292}293return goog.dom.getElementsByTagNameAndClass_(294document, '*', className, opt_el);295};296297298/**299* Returns the first element with the provided className.300*301* @param {string} className the name of the class to look for.302* @param {Element|Document=} opt_el Optional element to look in.303* @return {Element} The first item with the class name provided.304*/305goog.dom.getElementByClass = function(className, opt_el) {306'use strict';307var parent = opt_el || document;308var retVal = null;309if (parent.getElementsByClassName) {310retVal = parent.getElementsByClassName(className)[0];311} else {312retVal =313goog.dom.getElementByTagNameAndClass_(document, '*', className, opt_el);314}315return retVal || null;316};317318319/**320* Returns the first element with the provided className and asserts that it is321* an HTML element.322*323* @param {string} className the name of the class to look for.324* @param {!Element|!Document=} opt_parent Optional element to look in.325* @return {?HTMLElement} The first item with the class name provided.326*/327goog.dom.getHTMLElementByClass = function(className, opt_parent) {328'use strict'329const element = goog.dom.getElementByClass(className, opt_parent);330if (!element) {331return null;332}333return goog.asserts.dom.assertIsHtmlElement(element);334};335336337/**338* Ensures an element with the given className exists, and then returns the339* first element with the provided className.340*341* @param {string} className the name of the class to look for.342* @param {!Element|!Document=} opt_root Optional element or document to look343* in.344* @return {!Element} The first item with the class name provided.345* @throws {goog.asserts.AssertionError} Thrown if no element is found.346*/347goog.dom.getRequiredElementByClass = function(className, opt_root) {348'use strict';349var retValue = goog.dom.getElementByClass(className, opt_root);350return goog.asserts.assert(351retValue, 'No element found with className: ' + className);352};353354355/**356* Ensures an element with the given className exists, and then returns the357* first element with the provided className after asserting that it is an358* HTML element.359*360* @param {string} className the name of the class to look for.361* @param {!Element|!Document=} opt_parent Optional element or document to look362* in.363* @return {!HTMLElement} The first item with the class name provided.364*/365goog.dom.getRequiredHTMLElementByClass = function(className, opt_parent) {366'use strict'367const retValue = goog.dom.getElementByClass(className, opt_parent);368goog.asserts.assert(369retValue, 'No HTMLElement found with className: ' + className);370return goog.asserts.dom.assertIsHtmlElement(retValue);371};372373374/**375* Prefer the standardized (http://www.w3.org/TR/selectors-api/), native and376* fast W3C Selectors API.377* @param {!(Element|Document)} parent The parent document object.378* @return {boolean} whether or not we can use parent.querySelector* APIs.379* @private380*/381goog.dom.canUseQuerySelector_ = function(parent) {382'use strict';383return !!(parent.querySelectorAll && parent.querySelector);384};385386387/**388* Helper for `getElementsByTagNameAndClass`.389* @param {!Document} doc The document to get the elements in.390* @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.391* @param {?string=} opt_class Optional class name.392* @param {(Document|Element)=} opt_el Optional element to look in.393* @return {!IArrayLike<R>} Array-like list of elements (only a length property394* and numerical indices are guaranteed to exist). The members of the array395* are {!Element} if opt_tag is not a member of goog.dom.TagName or more396* specific types if it is (e.g. {!HTMLAnchorElement} for397* goog.dom.TagName.A).398* @template T399* @template R := cond(isUnknown(T), 'Element', T) =:400* @private401*/402goog.dom.getElementsByTagNameAndClass_ = function(403doc, opt_tag, opt_class, opt_el) {404'use strict';405var parent = opt_el || doc;406var tagName =407(opt_tag && opt_tag != '*') ? String(opt_tag).toUpperCase() : '';408409if (goog.dom.canUseQuerySelector_(parent) && (tagName || opt_class)) {410var query = tagName + (opt_class ? '.' + opt_class : '');411return parent.querySelectorAll(query);412}413414// Use the native getElementsByClassName if available, under the assumption415// that even when the tag name is specified, there will be fewer elements to416// filter through when going by class than by tag name417if (opt_class && parent.getElementsByClassName) {418var els = parent.getElementsByClassName(opt_class);419420if (tagName) {421var arrayLike = {};422var len = 0;423424// Filter for specific tags if requested.425for (var i = 0, el; el = els[i]; i++) {426if (tagName == el.nodeName) {427arrayLike[len++] = el;428}429}430arrayLike.length = len;431432return /** @type {!IArrayLike<!Element>} */ (arrayLike);433} else {434return els;435}436}437438var els = parent.getElementsByTagName(tagName || '*');439440if (opt_class) {441var arrayLike = {};442var len = 0;443for (var i = 0, el; el = els[i]; i++) {444var className = el.className;445// Check if className has a split function since SVG className does not.446if (typeof className.split == 'function' &&447goog.array.contains(className.split(/\s+/), opt_class)) {448arrayLike[len++] = el;449}450}451arrayLike.length = len;452return /** @type {!IArrayLike<!Element>} */ (arrayLike);453} else {454return els;455}456};457458459/**460* Helper for goog.dom.getElementByTagNameAndClass.461*462* @param {!Document} doc The document to get the elements in.463* @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.464* @param {?string=} opt_class Optional class name.465* @param {(Document|Element)=} opt_el Optional element to look in.466* @return {?R} Reference to a DOM node. The return type is {?Element} if467* tagName is a string or a more specific type if it is a member of468* goog.dom.TagName (e.g. {?HTMLAnchorElement} for goog.dom.TagName.A).469* @template T470* @template R := cond(isUnknown(T), 'Element', T) =:471* @private472*/473goog.dom.getElementByTagNameAndClass_ = function(474doc, opt_tag, opt_class, opt_el) {475'use strict';476var parent = opt_el || doc;477var tag = (opt_tag && opt_tag != '*') ? String(opt_tag).toUpperCase() : '';478if (goog.dom.canUseQuerySelector_(parent) && (tag || opt_class)) {479return parent.querySelector(tag + (opt_class ? '.' + opt_class : ''));480}481var elements =482goog.dom.getElementsByTagNameAndClass_(doc, opt_tag, opt_class, opt_el);483return elements[0] || null;484};485486487488/**489* Alias for `getElementsByTagNameAndClass`.490* @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.491* @param {?string=} opt_class Optional class name.492* @param {Element=} opt_el Optional element to look in.493* @return {!IArrayLike<R>} Array-like list of elements (only a length property494* and numerical indices are guaranteed to exist). The members of the array495* are {!Element} if opt_tag is not a member of goog.dom.TagName or more496* specific types if it is (e.g. {!HTMLAnchorElement} for497* goog.dom.TagName.A).498* @template T499* @template R := cond(isUnknown(T), 'Element', T) =:500* @deprecated Use {@link goog.dom.getElementsByTagNameAndClass} instead.501*/502goog.dom.$$ = goog.dom.getElementsByTagNameAndClass;503504505/**506* Sets multiple properties, and sometimes attributes, on an element. Note that507* properties are simply object properties on the element instance, while508* attributes are visible in the DOM. Many properties map to attributes with the509* same names, some with different names, and there are also unmappable cases.510*511* This method sets properties by default (which means that custom attributes512* are not supported). These are the exeptions (some of which is legacy):513* - "style": Even though this is an attribute name, it is translated to a514* property, "style.cssText". Note that this property sanitizes and formats515* its value, unlike the attribute.516* - "class": This is an attribute name, it is translated to the "className"517* property.518* - "for": This is an attribute name, it is translated to the "htmlFor"519* property.520* - Entries in {@see goog.dom.DIRECT_ATTRIBUTE_MAP_} are set as attributes,521* this is probably due to browser quirks.522* - "aria-*", "data-*": Always set as attributes, they have no property523* counterparts.524*525* @param {Element} element DOM node to set properties on.526* @param {Object} properties Hash of property:value pairs.527* Property values can be strings or goog.string.TypedString values (such as528* goog.html.SafeUrl).529*/530goog.dom.setProperties = function(element, properties) {531'use strict';532goog.object.forEach(properties, function(val, key) {533'use strict';534if (val && typeof val == 'object' && val.implementsGoogStringTypedString) {535val = val.getTypedStringValue();536}537if (key == 'style') {538element.style.cssText = val;539} else if (key == 'class') {540element.className = val;541} else if (key == 'for') {542element.htmlFor = val;543} else if (goog.dom.DIRECT_ATTRIBUTE_MAP_.hasOwnProperty(key)) {544element.setAttribute(goog.dom.DIRECT_ATTRIBUTE_MAP_[key], val);545} else if (546goog.string.startsWith(key, 'aria-') ||547goog.string.startsWith(key, 'data-')) {548element.setAttribute(key, val);549} else {550element[key] = val;551}552});553};554555556/**557* Map of attributes that should be set using558* element.setAttribute(key, val) instead of element[key] = val. Used559* by goog.dom.setProperties.560*561* @private {!Object<string, string>}562* @const563*/564goog.dom.DIRECT_ATTRIBUTE_MAP_ = {565'cellpadding': 'cellPadding',566'cellspacing': 'cellSpacing',567'colspan': 'colSpan',568'frameborder': 'frameBorder',569'height': 'height',570'maxlength': 'maxLength',571'nonce': 'nonce',572'role': 'role',573'rowspan': 'rowSpan',574'type': 'type',575'usemap': 'useMap',576'valign': 'vAlign',577'width': 'width'578};579580581/**582* Gets the dimensions of the viewport.583*584* Gecko Standards mode:585* docEl.clientWidth Width of viewport excluding scrollbar.586* win.innerWidth Width of viewport including scrollbar.587* body.clientWidth Width of body element.588*589* docEl.clientHeight Height of viewport excluding scrollbar.590* win.innerHeight Height of viewport including scrollbar.591* body.clientHeight Height of document.592*593* Gecko Backwards compatible mode:594* docEl.clientWidth Width of viewport excluding scrollbar.595* win.innerWidth Width of viewport including scrollbar.596* body.clientWidth Width of viewport excluding scrollbar.597*598* docEl.clientHeight Height of document.599* win.innerHeight Height of viewport including scrollbar.600* body.clientHeight Height of viewport excluding scrollbar.601*602* IE6/7 Standards mode:603* docEl.clientWidth Width of viewport excluding scrollbar.604* win.innerWidth Undefined.605* body.clientWidth Width of body element.606*607* docEl.clientHeight Height of viewport excluding scrollbar.608* win.innerHeight Undefined.609* body.clientHeight Height of document element.610*611* IE5 + IE6/7 Backwards compatible mode:612* docEl.clientWidth 0.613* win.innerWidth Undefined.614* body.clientWidth Width of viewport excluding scrollbar.615*616* docEl.clientHeight 0.617* win.innerHeight Undefined.618* body.clientHeight Height of viewport excluding scrollbar.619*620* Opera 9 Standards and backwards compatible mode:621* docEl.clientWidth Width of viewport excluding scrollbar.622* win.innerWidth Width of viewport including scrollbar.623* body.clientWidth Width of viewport excluding scrollbar.624*625* docEl.clientHeight Height of document.626* win.innerHeight Height of viewport including scrollbar.627* body.clientHeight Height of viewport excluding scrollbar.628*629* WebKit:630* Safari 2631* docEl.clientHeight Same as scrollHeight.632* docEl.clientWidth Same as innerWidth.633* win.innerWidth Width of viewport excluding scrollbar.634* win.innerHeight Height of the viewport including scrollbar.635* frame.innerHeight Height of the viewport excluding scrollbar.636*637* Safari 3 (tested in 522)638*639* docEl.clientWidth Width of viewport excluding scrollbar.640* docEl.clientHeight Height of viewport excluding scrollbar in strict mode.641* body.clientHeight Height of viewport excluding scrollbar in quirks mode.642*643* @param {Window=} opt_window Optional window element to test.644* @return {!goog.math.Size} Object with values 'width' and 'height'.645*/646goog.dom.getViewportSize = function(opt_window) {647'use strict';648// TODO(arv): This should not take an argument649return goog.dom.getViewportSize_(opt_window || window);650};651652653/**654* Helper for `getViewportSize`.655* @param {Window} win The window to get the view port size for.656* @return {!goog.math.Size} Object with values 'width' and 'height'.657* @private658*/659goog.dom.getViewportSize_ = function(win) {660'use strict';661var doc = win.document;662var el = goog.dom.isCss1CompatMode_(doc) ? doc.documentElement : doc.body;663return new goog.math.Size(el.clientWidth, el.clientHeight);664};665666667/**668* Calculates the height of the document.669*670* @return {number} The height of the current document.671*/672goog.dom.getDocumentHeight = function() {673'use strict';674return goog.dom.getDocumentHeight_(window);675};676677/**678* Calculates the height of the document of the given window.679*680* @param {!Window} win The window whose document height to retrieve.681* @return {number} The height of the document of the given window.682*/683goog.dom.getDocumentHeightForWindow = function(win) {684'use strict';685return goog.dom.getDocumentHeight_(win);686};687688/**689* Calculates the height of the document of the given window.690*691* Function code copied from the opensocial gadget api:692* gadgets.window.adjustHeight(opt_height)693*694* @private695* @param {!Window} win The window whose document height to retrieve.696* @return {number} The height of the document of the given window.697*/698goog.dom.getDocumentHeight_ = function(win) {699'use strict';700// NOTE(eae): This method will return the window size rather than the document701// size in webkit quirks mode.702var doc = win.document;703var height = 0;704705if (doc) {706// Calculating inner content height is hard and different between707// browsers rendering in Strict vs. Quirks mode. We use a combination of708// three properties within document.body and document.documentElement:709// - scrollHeight710// - offsetHeight711// - clientHeight712// These values differ significantly between browsers and rendering modes.713// But there are patterns. It just takes a lot of time and persistence714// to figure out.715716var body = doc.body;717var docEl = /** @type {!HTMLElement} */ (doc.documentElement);718if (!(docEl && body)) {719return 0;720}721722// Get the height of the viewport723var vh = goog.dom.getViewportSize_(win).height;724if (goog.dom.isCss1CompatMode_(doc) && docEl.scrollHeight) {725// In Strict mode:726// The inner content height is contained in either:727// document.documentElement.scrollHeight728// document.documentElement.offsetHeight729// Based on studying the values output by different browsers,730// use the value that's NOT equal to the viewport height found above.731height =732docEl.scrollHeight != vh ? docEl.scrollHeight : docEl.offsetHeight;733} else {734// In Quirks mode:735// documentElement.clientHeight is equal to documentElement.offsetHeight736// except in IE. In most browsers, document.documentElement can be used737// to calculate the inner content height.738// However, in other browsers (e.g. IE), document.body must be used739// instead. How do we know which one to use?740// If document.documentElement.clientHeight does NOT equal741// document.documentElement.offsetHeight, then use document.body.742var sh = docEl.scrollHeight;743var oh = docEl.offsetHeight;744if (docEl.clientHeight != oh) {745sh = body.scrollHeight;746oh = body.offsetHeight;747}748749// Detect whether the inner content height is bigger or smaller750// than the bounding box (viewport). If bigger, take the larger751// value. If smaller, take the smaller value.752if (sh > vh) {753// Content is larger754height = sh > oh ? sh : oh;755} else {756// Content is smaller757height = sh < oh ? sh : oh;758}759}760}761762return height;763};764765766/**767* Gets the page scroll distance as a coordinate object.768*769* @param {Window=} opt_window Optional window element to test.770* @return {!goog.math.Coordinate} Object with values 'x' and 'y'.771* @deprecated Use {@link goog.dom.getDocumentScroll} instead.772*/773goog.dom.getPageScroll = function(opt_window) {774'use strict';775var win = opt_window || goog.global || window;776return goog.dom.getDomHelper(win.document).getDocumentScroll();777};778779780/**781* Gets the document scroll distance as a coordinate object.782*783* @return {!goog.math.Coordinate} Object with values 'x' and 'y'.784*/785goog.dom.getDocumentScroll = function() {786'use strict';787return goog.dom.getDocumentScroll_(document);788};789790791/**792* Helper for `getDocumentScroll`.793*794* @param {!Document} doc The document to get the scroll for.795* @return {!goog.math.Coordinate} Object with values 'x' and 'y'.796* @private797*/798goog.dom.getDocumentScroll_ = function(doc) {799'use strict';800var el = goog.dom.getDocumentScrollElement_(doc);801var win = goog.dom.getWindow_(doc);802if (goog.userAgent.IE && win.pageYOffset != el.scrollTop) {803// The keyboard on IE10 touch devices shifts the page using the pageYOffset804// without modifying scrollTop. For this case, we want the body scroll805// offsets.806return new goog.math.Coordinate(el.scrollLeft, el.scrollTop);807}808return new goog.math.Coordinate(809win.pageXOffset || el.scrollLeft, win.pageYOffset || el.scrollTop);810};811812813/**814* Gets the document scroll element.815* @return {!Element} Scrolling element.816*/817goog.dom.getDocumentScrollElement = function() {818'use strict';819return goog.dom.getDocumentScrollElement_(document);820};821822823/**824* Helper for `getDocumentScrollElement`.825* @param {!Document} doc The document to get the scroll element for.826* @return {!Element} Scrolling element.827* @private828*/829goog.dom.getDocumentScrollElement_ = function(doc) {830'use strict';831// Old WebKit needs body.scrollLeft in both quirks mode and strict mode. We832// also default to the documentElement if the document does not have a body833// (e.g. a SVG document).834// Uses http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement to835// avoid trying to guess about browser behavior from the UA string.836if (doc.scrollingElement) {837return doc.scrollingElement;838}839if (!goog.userAgent.WEBKIT && goog.dom.isCss1CompatMode_(doc)) {840return doc.documentElement;841}842return doc.body || doc.documentElement;843};844845846/**847* Gets the window object associated with the given document.848*849* @param {Document=} opt_doc Document object to get window for.850* @return {!Window} The window associated with the given document.851*/852goog.dom.getWindow = function(opt_doc) {853'use strict';854// TODO(arv): This should not take an argument.855return opt_doc ? goog.dom.getWindow_(opt_doc) : window;856};857858859/**860* Helper for `getWindow`.861*862* @param {!Document} doc Document object to get window for.863* @return {!Window} The window associated with the given document.864* @private865*/866goog.dom.getWindow_ = function(doc) {867'use strict';868return /** @type {!Window} */ (doc.parentWindow || doc.defaultView);869};870871872/**873* Returns a dom node with a set of attributes. This function accepts varargs874* for subsequent nodes to be added. Subsequent nodes will be added to the875* first node as childNodes.876*877* So:878* <code>createDom(goog.dom.TagName.DIV, null, createDom(goog.dom.TagName.P),879* createDom(goog.dom.TagName.P));</code> would return a div with two child880* paragraphs881*882* This function uses {@link goog.dom.setProperties} to set attributes: the883* `opt_attributes` parameter follows the same rules.884*885* @param {string|!goog.dom.TagName<T>} tagName Tag to create.886* @param {?Object|?Array<string>|string=} opt_attributes If object, then a map887* of name-value pairs for attributes. If a string, then this is the888* className of the new element. If an array, the elements will be joined889* together as the className of the new element.890* @param {...(Object|string|Array|NodeList|null|undefined)} var_args Further891* DOM nodes or strings for text nodes. If one of the var_args is an array892* or NodeList, its elements will be added as childNodes instead.893* @return {R} Reference to a DOM node. The return type is {!Element} if tagName894* is a string or a more specific type if it is a member of895* goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).896* @template T897* @template R := cond(isUnknown(T), 'Element', T) =:898*/899goog.dom.createDom = function(tagName, opt_attributes, var_args) {900'use strict';901return goog.dom.createDom_(document, arguments);902};903904905/**906* Helper for `createDom`.907* @param {!Document} doc The document to create the DOM in.908* @param {!Arguments} args Argument object passed from the callers. See909* `goog.dom.createDom` for details.910* @return {!Element} Reference to a DOM node.911* @private912*/913goog.dom.createDom_ = function(doc, args) {914'use strict';915var tagName = String(args[0]);916var attributes = args[1];917918var element = goog.dom.createElement_(doc, tagName);919920if (attributes) {921if (typeof attributes === 'string') {922element.className = attributes;923} else if (Array.isArray(attributes)) {924element.className = attributes.join(' ');925} else {926goog.dom.setProperties(element, attributes);927}928}929930if (args.length > 2) {931goog.dom.append_(doc, element, args, 2);932}933934return element;935};936937938/**939* Appends a node with text or other nodes.940* @param {!Document} doc The document to create new nodes in.941* @param {!Node} parent The node to append nodes to.942* @param {!Arguments} args The values to add. See `goog.dom.append`.943* @param {number} startIndex The index of the array to start from.944* @private945*/946goog.dom.append_ = function(doc, parent, args, startIndex) {947'use strict';948function childHandler(child) {949// TODO(user): More coercion, ala MochiKit?950if (child) {951parent.appendChild(952typeof child === 'string' ? doc.createTextNode(child) : child);953}954}955956for (var i = startIndex; i < args.length; i++) {957var arg = args[i];958// TODO(attila): Fix isArrayLike to return false for a text node.959if (goog.utils.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) {960// If the argument is a node list, not a real array, use a clone,961// because forEach can't be used to mutate a NodeList.962goog.array.forEach(963goog.dom.isNodeList(arg) ? goog.array.toArray(arg) : arg,964childHandler);965} else {966childHandler(arg);967}968}969};970971972/**973* Alias for `createDom`.974* @param {string|!goog.dom.TagName<T>} tagName Tag to create.975* @param {?Object|?Array<string>|string=} opt_attributes If object, then a map976* of name-value pairs for attributes. If a string, then this is the977* className of the new element. If an array, the elements will be joined978* together as the className of the new element.979* @param {...(Object|string|Array|NodeList|null|undefined)} var_args Further980* DOM nodes or strings for text nodes. If one of the var_args is an array,981* its children will be added as childNodes instead.982* @return {R} Reference to a DOM node. The return type is {!Element} if tagName983* is a string or a more specific type if it is a member of984* goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).985* @template T986* @template R := cond(isUnknown(T), 'Element', T) =:987* @deprecated Use {@link goog.dom.createDom} instead.988*/989goog.dom.$dom = goog.dom.createDom;990991992/**993* Creates a new element.994* @param {string|!goog.dom.TagName<T>} name Tag to create.995* @return {R} The new element. The return type is {!Element} if name is996* a string or a more specific type if it is a member of goog.dom.TagName997* (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).998* @template T999* @template R := cond(isUnknown(T), 'Element', T) =:1000*/1001goog.dom.createElement = function(name) {1002'use strict';1003return goog.dom.createElement_(document, name);1004};100510061007/**1008* Creates a new element.1009* @param {!Document} doc The document to create the element in.1010* @param {string|!goog.dom.TagName<T>} name Tag to create.1011* @return {R} The new element. The return type is {!Element} if name is1012* a string or a more specific type if it is a member of goog.dom.TagName1013* (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).1014* @template T1015* @template R := cond(isUnknown(T), 'Element', T) =:1016* @private1017*/1018goog.dom.createElement_ = function(doc, name) {1019'use strict';1020name = String(name);1021if (doc.contentType === 'application/xhtml+xml') name = name.toLowerCase();1022return doc.createElement(name);1023};102410251026/**1027* Creates a new text node.1028* @param {number|string} content Content.1029* @return {!Text} The new text node.1030*/1031goog.dom.createTextNode = function(content) {1032'use strict';1033return document.createTextNode(String(content));1034};103510361037/**1038* Create a table.1039* @param {number} rows The number of rows in the table. Must be >= 1.1040* @param {number} columns The number of columns in the table. Must be >= 1.1041* @param {boolean=} opt_fillWithNbsp If true, fills table entries with1042* `goog.string.Unicode.NBSP` characters.1043* @return {!Element} The created table.1044*/1045goog.dom.createTable = function(rows, columns, opt_fillWithNbsp) {1046'use strict';1047// TODO(mlourenco): Return HTMLTableElement, also in prototype function.1048// Callers need to be updated to e.g. not assign numbers to table.cellSpacing.1049return goog.dom.createTable_(document, rows, columns, !!opt_fillWithNbsp);1050};105110521053/**1054* Create a table.1055* @param {!Document} doc Document object to use to create the table.1056* @param {number} rows The number of rows in the table. Must be >= 1.1057* @param {number} columns The number of columns in the table. Must be >= 1.1058* @param {boolean} fillWithNbsp If true, fills table entries with1059* `goog.string.Unicode.NBSP` characters.1060* @return {!HTMLTableElement} The created table.1061* @private1062*/1063goog.dom.createTable_ = function(doc, rows, columns, fillWithNbsp) {1064'use strict';1065var table = goog.dom.createElement_(doc, goog.dom.TagName.TABLE);1066var tbody =1067table.appendChild(goog.dom.createElement_(doc, goog.dom.TagName.TBODY));1068for (var i = 0; i < rows; i++) {1069var tr = goog.dom.createElement_(doc, goog.dom.TagName.TR);1070for (var j = 0; j < columns; j++) {1071var td = goog.dom.createElement_(doc, goog.dom.TagName.TD);1072// IE <= 9 will create a text node if we set text content to the empty1073// string, so we avoid doing it unless necessary. This ensures that the1074// same DOM tree is returned on all browsers.1075if (fillWithNbsp) {1076goog.dom.setTextContent(td, goog.string.Unicode.NBSP);1077}1078tr.appendChild(td);1079}1080tbody.appendChild(tr);1081}1082return table;1083};1084108510861087/**1088* Creates a new Node from constant strings of HTML markup.1089* @param {...!goog.string.Const} var_args The HTML strings to concatenate then1090* convert into a node.1091* @return {!Node}1092*/1093goog.dom.constHtmlToNode = function(var_args) {1094'use strict';1095var stringArray =1096Array.prototype.map.call(arguments, goog.string.Const.unwrap);1097var safeHtml =1098goog.html.uncheckedconversions1099.safeHtmlFromStringKnownToSatisfyTypeContract(1100goog.string.Const.from(1101'Constant HTML string, that gets turned into a ' +1102'Node later, so it will be automatically balanced.'),1103stringArray.join(''));1104return goog.dom.safeHtmlToNode(safeHtml);1105};110611071108/**1109* Converts HTML markup into a node. This is a safe version of1110* `goog.dom.htmlToDocumentFragment` which is now deleted.1111* @param {!goog.html.SafeHtml} html The HTML markup to convert.1112* @return {!Node} The resulting node.1113*/1114goog.dom.safeHtmlToNode = function(html) {1115'use strict';1116return goog.dom.safeHtmlToNode_(document, html);1117};111811191120/**1121* Helper for `safeHtmlToNode`.1122* @param {!Document} doc The document.1123* @param {!goog.html.SafeHtml} html The HTML markup to convert.1124* @return {!Node} The resulting node.1125* @private1126*/1127goog.dom.safeHtmlToNode_ = function(doc, html) {1128'use strict';1129var tempDiv = goog.dom.createElement_(doc, goog.dom.TagName.DIV);1130if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) {1131goog.dom.safe.setInnerHtml(1132tempDiv, goog.html.SafeHtml.concat(goog.html.SafeHtml.BR, html));1133tempDiv.removeChild(goog.asserts.assert(tempDiv.firstChild));1134} else {1135goog.dom.safe.setInnerHtml(tempDiv, html);1136}1137return goog.dom.childrenToNode_(doc, tempDiv);1138};113911401141/**1142* Helper for `safeHtmlToNode_`.1143* @param {!Document} doc The document.1144* @param {!Node} tempDiv The input node.1145* @return {!Node} The resulting node.1146* @private1147*/1148goog.dom.childrenToNode_ = function(doc, tempDiv) {1149'use strict';1150if (tempDiv.childNodes.length == 1) {1151return tempDiv.removeChild(goog.asserts.assert(tempDiv.firstChild));1152} else {1153var fragment = doc.createDocumentFragment();1154while (tempDiv.firstChild) {1155fragment.appendChild(tempDiv.firstChild);1156}1157return fragment;1158}1159};116011611162/**1163* Returns true if the browser is in "CSS1-compatible" (standards-compliant)1164* mode, false otherwise.1165* @return {boolean} True if in CSS1-compatible mode.1166*/1167goog.dom.isCss1CompatMode = function() {1168'use strict';1169return goog.dom.isCss1CompatMode_(document);1170};117111721173/**1174* Returns true if the browser is in "CSS1-compatible" (standards-compliant)1175* mode, false otherwise.1176* @param {!Document} doc The document to check.1177* @return {boolean} True if in CSS1-compatible mode.1178* @private1179*/1180goog.dom.isCss1CompatMode_ = function(doc) {1181'use strict';1182if (goog.dom.COMPAT_MODE_KNOWN_) {1183return goog.dom.ASSUME_STANDARDS_MODE;1184}11851186return doc.compatMode == 'CSS1Compat';1187};118811891190/**1191* Determines if the given node can contain children, intended to be used for1192* HTML generation.1193*1194* IE natively supports node.canHaveChildren but has inconsistent behavior.1195* Prior to IE8 the base tag allows children and in IE9 all nodes return true1196* for canHaveChildren.1197*1198* In practice all non-IE browsers allow you to add children to any node, but1199* the behavior is inconsistent:1200*1201* <pre>1202* var a = goog.dom.createElement(goog.dom.TagName.BR);1203* a.appendChild(document.createTextNode('foo'));1204* a.appendChild(document.createTextNode('bar'));1205* console.log(a.childNodes.length); // 21206* console.log(a.innerHTML); // Chrome: "", IE9: "foobar", FF3.5: "foobar"1207* </pre>1208*1209* For more information, see:1210* http://dev.w3.org/html5/markup/syntax.html#syntax-elements1211*1212* TODO(user): Rename shouldAllowChildren() ?1213*1214* @param {Node} node The node to check.1215* @return {boolean} Whether the node can contain children.1216*/1217goog.dom.canHaveChildren = function(node) {1218'use strict';1219if (node.nodeType != goog.dom.NodeType.ELEMENT) {1220return false;1221}1222switch (/** @type {!Element} */ (node).tagName) {1223case String(goog.dom.TagName.APPLET):1224case String(goog.dom.TagName.AREA):1225case String(goog.dom.TagName.BASE):1226case String(goog.dom.TagName.BR):1227case String(goog.dom.TagName.COL):1228case String(goog.dom.TagName.COMMAND):1229case String(goog.dom.TagName.EMBED):1230case String(goog.dom.TagName.FRAME):1231case String(goog.dom.TagName.HR):1232case String(goog.dom.TagName.IMG):1233case String(goog.dom.TagName.INPUT):1234case String(goog.dom.TagName.IFRAME):1235case String(goog.dom.TagName.ISINDEX):1236case String(goog.dom.TagName.KEYGEN):1237case String(goog.dom.TagName.LINK):1238case String(goog.dom.TagName.NOFRAMES):1239case String(goog.dom.TagName.NOSCRIPT):1240case String(goog.dom.TagName.META):1241case String(goog.dom.TagName.OBJECT):1242case String(goog.dom.TagName.PARAM):1243case String(goog.dom.TagName.SCRIPT):1244case String(goog.dom.TagName.SOURCE):1245case String(goog.dom.TagName.STYLE):1246case String(goog.dom.TagName.TRACK):1247case String(goog.dom.TagName.WBR):1248return false;1249}1250return true;1251};125212531254/**1255* Appends a child to a node.1256* @param {Node} parent Parent.1257* @param {Node} child Child.1258*/1259goog.dom.appendChild = function(parent, child) {1260'use strict';1261goog.asserts.assert(1262parent != null && child != null,1263'goog.dom.appendChild expects non-null arguments');1264parent.appendChild(child);1265};126612671268/**1269* Appends a node with text or other nodes.1270* @param {!Node} parent The node to append nodes to.1271* @param {...goog.dom.Appendable} var_args The things to append to the node.1272* If this is a Node it is appended as is.1273* If this is a string then a text node is appended.1274* If this is an array like object then fields 0 to length - 1 are appended.1275*/1276goog.dom.append = function(parent, var_args) {1277'use strict';1278goog.dom.append_(goog.dom.getOwnerDocument(parent), parent, arguments, 1);1279};128012811282/**1283* Removes all the child nodes on a DOM node.1284* @param {Node} node Node to remove children from.1285* @return {void}1286*/1287goog.dom.removeChildren = function(node) {1288'use strict';1289// Note: Iterations over live collections can be slow, this is the fastest1290// we could find. The double parenthesis are used to prevent JsCompiler and1291// strict warnings.1292var child;1293while ((child = node.firstChild)) {1294node.removeChild(child);1295}1296};129712981299/**1300* Inserts a new node before an existing reference node (i.e. as the previous1301* sibling). If the reference node has no parent, then does nothing.1302* @param {Node} newNode Node to insert.1303* @param {Node} refNode Reference node to insert before.1304*/1305goog.dom.insertSiblingBefore = function(newNode, refNode) {1306'use strict';1307goog.asserts.assert(1308newNode != null && refNode != null,1309'goog.dom.insertSiblingBefore expects non-null arguments');1310if (refNode.parentNode) {1311refNode.parentNode.insertBefore(newNode, refNode);1312}1313};131413151316/**1317* Inserts a new node after an existing reference node (i.e. as the next1318* sibling). If the reference node has no parent, then does nothing.1319* @param {Node} newNode Node to insert.1320* @param {Node} refNode Reference node to insert after.1321* @return {void}1322*/1323goog.dom.insertSiblingAfter = function(newNode, refNode) {1324'use strict';1325goog.asserts.assert(1326newNode != null && refNode != null,1327'goog.dom.insertSiblingAfter expects non-null arguments');1328if (refNode.parentNode) {1329refNode.parentNode.insertBefore(newNode, refNode.nextSibling);1330}1331};133213331334/**1335* Insert a child at a given index. If index is larger than the number of child1336* nodes that the parent currently has, the node is inserted as the last child1337* node.1338* @param {Element} parent The element into which to insert the child.1339* @param {Node} child The element to insert.1340* @param {number} index The index at which to insert the new child node. Must1341* not be negative.1342* @return {void}1343*/1344goog.dom.insertChildAt = function(parent, child, index) {1345'use strict';1346// Note that if the second argument is null, insertBefore1347// will append the child at the end of the list of children.1348goog.asserts.assert(1349parent != null, 'goog.dom.insertChildAt expects a non-null parent');1350parent.insertBefore(1351/** @type {!Node} */ (child), parent.childNodes[index] || null);1352};135313541355/**1356* Removes a node from its parent.1357* @param {Node} node The node to remove.1358* @return {Node} The node removed if removed; else, null.1359*/1360goog.dom.removeNode = function(node) {1361'use strict';1362return node && node.parentNode ? node.parentNode.removeChild(node) : null;1363};136413651366/**1367* Replaces a node in the DOM tree. Will do nothing if `oldNode` has no1368* parent.1369* @param {Node} newNode Node to insert.1370* @param {Node} oldNode Node to replace.1371*/1372goog.dom.replaceNode = function(newNode, oldNode) {1373'use strict';1374goog.asserts.assert(1375newNode != null && oldNode != null,1376'goog.dom.replaceNode expects non-null arguments');1377var parent = oldNode.parentNode;1378if (parent) {1379parent.replaceChild(newNode, oldNode);1380}1381};138213831384/**1385* Replaces child nodes of `target` with child nodes of `source`. This is1386* roughly equivalent to `target.innerHTML = source.innerHTML` which is not1387* compatible with Trusted Types.1388* @param {?Node} target Node to clean and replace its children.1389* @param {?Node} source Node to get the children from. The nodes will be cloned1390* so they will stay in source.1391*/1392goog.dom.copyContents = function(target, source) {1393'use strict';1394goog.asserts.assert(1395target != null && source != null,1396'goog.dom.copyContents expects non-null arguments');1397var childNodes = source.cloneNode(/* deep= */ true).childNodes;1398goog.dom.removeChildren(target);1399while (childNodes.length) {1400target.appendChild(childNodes[0]);1401}1402};140314041405/**1406* Flattens an element. That is, removes it and replace it with its children.1407* Does nothing if the element is not in the document.1408* @param {Element} element The element to flatten.1409* @return {Element|undefined} The original element, detached from the document1410* tree, sans children; or undefined, if the element was not in the document1411* to begin with.1412*/1413goog.dom.flattenElement = function(element) {1414'use strict';1415var child, parent = element.parentNode;1416if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) {1417// Use IE DOM method (supported by Opera too) if available1418if (element.removeNode) {1419return /** @type {Element} */ (element.removeNode(false));1420} else {1421// Move all children of the original node up one level.1422while ((child = element.firstChild)) {1423parent.insertBefore(child, element);1424}14251426// Detach the original element.1427return /** @type {Element} */ (goog.dom.removeNode(element));1428}1429}1430};143114321433/**1434* Returns an array containing just the element children of the given element.1435* @param {Element} element The element whose element children we want.1436* @return {!(Array<!Element>|NodeList<!Element>)} An array or array-like list1437* of just the element children of the given element.1438*/1439goog.dom.getChildren = function(element) {1440'use strict';1441// We check if the children attribute is supported for child elements1442// since IE8 misuses the attribute by also including comments.1443if (element.children != undefined) {1444return element.children;1445}1446// Fall back to manually filtering the element's child nodes.1447return Array.prototype.filter.call(element.childNodes, function(node) {1448return node.nodeType == goog.dom.NodeType.ELEMENT;1449});1450};145114521453/**1454* Returns the first child node that is an element.1455* @param {Node} node The node to get the first child element of.1456* @return {Element} The first child node of `node` that is an element.1457*/1458goog.dom.getFirstElementChild = function(node) {1459'use strict';1460if (node.firstElementChild !== undefined) {1461return /** @type {!Element} */ (node).firstElementChild;1462}1463return goog.dom.getNextElementNode_(node.firstChild, true);1464};146514661467/**1468* Returns the last child node that is an element.1469* @param {Node} node The node to get the last child element of.1470* @return {Element} The last child node of `node` that is an element.1471*/1472goog.dom.getLastElementChild = function(node) {1473'use strict';1474if (node.lastElementChild !== undefined) {1475return /** @type {!Element} */ (node).lastElementChild;1476}1477return goog.dom.getNextElementNode_(node.lastChild, false);1478};147914801481/**1482* Returns the first next sibling that is an element.1483* @param {Node} node The node to get the next sibling element of.1484* @return {Element} The next sibling of `node` that is an element.1485*/1486goog.dom.getNextElementSibling = function(node) {1487'use strict';1488if (node.nextElementSibling !== undefined) {1489return /** @type {!Element} */ (node).nextElementSibling;1490}1491return goog.dom.getNextElementNode_(node.nextSibling, true);1492};149314941495/**1496* Returns the first previous sibling that is an element.1497* @param {Node} node The node to get the previous sibling element of.1498* @return {Element} The first previous sibling of `node` that is1499* an element.1500*/1501goog.dom.getPreviousElementSibling = function(node) {1502'use strict';1503if (node.previousElementSibling !== undefined) {1504return /** @type {!Element} */ (node).previousElementSibling;1505}1506return goog.dom.getNextElementNode_(node.previousSibling, false);1507};150815091510/**1511* Returns the first node that is an element in the specified direction,1512* starting with `node`.1513* @param {Node} node The node to get the next element from.1514* @param {boolean} forward Whether to look forwards or backwards.1515* @return {Element} The first element.1516* @private1517*/1518goog.dom.getNextElementNode_ = function(node, forward) {1519'use strict';1520while (node && node.nodeType != goog.dom.NodeType.ELEMENT) {1521node = forward ? node.nextSibling : node.previousSibling;1522}15231524return /** @type {Element} */ (node);1525};152615271528/**1529* Returns the next node in source order from the given node.1530* @param {Node} node The node.1531* @return {Node} The next node in the DOM tree, or null if this was the last1532* node.1533*/1534goog.dom.getNextNode = function(node) {1535'use strict';1536if (!node) {1537return null;1538}15391540if (node.firstChild) {1541return node.firstChild;1542}15431544while (node && !node.nextSibling) {1545node = node.parentNode;1546}15471548return node ? node.nextSibling : null;1549};155015511552/**1553* Returns the previous node in source order from the given node.1554* @param {Node} node The node.1555* @return {Node} The previous node in the DOM tree, or null if this was the1556* first node.1557*/1558goog.dom.getPreviousNode = function(node) {1559'use strict';1560if (!node) {1561return null;1562}15631564if (!node.previousSibling) {1565return node.parentNode;1566}15671568node = node.previousSibling;1569while (node && node.lastChild) {1570node = node.lastChild;1571}15721573return node;1574};157515761577/**1578* Whether the object looks like a DOM node.1579* @param {?} obj The object being tested for node likeness.1580* @return {boolean} Whether the object looks like a DOM node.1581*/1582goog.dom.isNodeLike = function(obj) {1583'use strict';1584return goog.utils.isObject(obj) && obj.nodeType > 0;1585};158615871588/**1589* Whether the object looks like an Element.1590* @param {?} obj The object being tested for Element likeness.1591* @return {boolean} Whether the object looks like an Element.1592*/1593goog.dom.isElement = function(obj) {1594'use strict';1595return goog.utils.isObject(obj) && obj.nodeType == goog.dom.NodeType.ELEMENT;1596};159715981599/**1600* Returns true if the specified value is a Window object. This includes the1601* global window for HTML pages, and iframe windows.1602* @param {?} obj Variable to test.1603* @return {boolean} Whether the variable is a window.1604*/1605goog.dom.isWindow = function(obj) {1606'use strict';1607return goog.utils.isObject(obj) && obj['window'] == obj;1608};160916101611/**1612* Returns an element's parent, if it's an Element.1613* @param {Element} element The DOM element.1614* @return {Element} The parent, or null if not an Element.1615*/1616goog.dom.getParentElement = function(element) {1617'use strict';1618var parent;1619if (goog.dom.BrowserFeature.CAN_USE_PARENT_ELEMENT_PROPERTY) {1620parent = element.parentElement;1621if (parent) {1622return parent;1623}1624}1625parent = element.parentNode;1626return goog.dom.isElement(parent) ? /** @type {!Element} */ (parent) : null;1627};162816291630/**1631* Whether a node contains another node.1632* @param {?Node|undefined} parent The node that should contain the other node.1633* @param {?Node|undefined} descendant The node to test presence of.1634* @return {boolean} Whether the parent node contains the descendant node.1635*/1636goog.dom.contains = function(parent, descendant) {1637'use strict';1638if (!parent || !descendant) {1639return false;1640}1641// We use browser specific methods for this if available since it is faster1642// that way.16431644// IE DOM1645if (parent.contains && descendant.nodeType == goog.dom.NodeType.ELEMENT) {1646return parent == descendant || parent.contains(descendant);1647}16481649// W3C DOM Level 31650if (typeof parent.compareDocumentPosition != 'undefined') {1651return parent == descendant ||1652Boolean(parent.compareDocumentPosition(descendant) & 16);1653}16541655// W3C DOM Level 11656while (descendant && parent != descendant) {1657descendant = descendant.parentNode;1658}1659return descendant == parent;1660};166116621663/**1664* Compares the document order of two nodes, returning 0 if they are the same1665* node, a negative number if node1 is before node2, and a positive number if1666* node2 is before node1. Note that we compare the order the tags appear in the1667* document so in the tree <b><i>text</i></b> the B node is considered to be1668* before the I node.1669*1670* @param {Node} node1 The first node to compare.1671* @param {Node} node2 The second node to compare.1672* @return {number} 0 if the nodes are the same node, a negative number if node11673* is before node2, and a positive number if node2 is before node1.1674*/1675goog.dom.compareNodeOrder = function(node1, node2) {1676'use strict';1677// Fall out quickly for equality.1678if (node1 == node2) {1679return 0;1680}16811682// Use compareDocumentPosition where available1683if (node1.compareDocumentPosition) {1684// 4 is the bitmask for FOLLOWS.1685return node1.compareDocumentPosition(node2) & 2 ? 1 : -1;1686}16871688// Special case for document nodes on IE 7 and 8.1689if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) {1690if (node1.nodeType == goog.dom.NodeType.DOCUMENT) {1691return -1;1692}1693if (node2.nodeType == goog.dom.NodeType.DOCUMENT) {1694return 1;1695}1696}16971698// Process in IE using sourceIndex - we check to see if the first node has1699// a source index or if its parent has one.1700if ('sourceIndex' in node1 ||1701(node1.parentNode && 'sourceIndex' in node1.parentNode)) {1702var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT;1703var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT;17041705if (isElement1 && isElement2) {1706return node1.sourceIndex - node2.sourceIndex;1707} else {1708var parent1 = node1.parentNode;1709var parent2 = node2.parentNode;17101711if (parent1 == parent2) {1712return goog.dom.compareSiblingOrder_(node1, node2);1713}17141715if (!isElement1 && goog.dom.contains(parent1, node2)) {1716return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2);1717}171817191720if (!isElement2 && goog.dom.contains(parent2, node1)) {1721return goog.dom.compareParentsDescendantNodeIe_(node2, node1);1722}17231724return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) -1725(isElement2 ? node2.sourceIndex : parent2.sourceIndex);1726}1727}17281729// For Safari, we compare ranges.1730var doc = goog.dom.getOwnerDocument(node1);17311732var range1, range2;1733range1 = doc.createRange();1734range1.selectNode(node1);1735range1.collapse(true);17361737range2 = doc.createRange();1738range2.selectNode(node2);1739range2.collapse(true);17401741return range1.compareBoundaryPoints(1742goog.global['Range'].START_TO_END, range2);1743};174417451746/**1747* Utility function to compare the position of two nodes, when1748* `textNode`'s parent is an ancestor of `node`. If this entry1749* condition is not met, this function will attempt to reference a null object.1750* @param {!Node} textNode The textNode to compare.1751* @param {Node} node The node to compare.1752* @return {number} -1 if node is before textNode, +1 otherwise.1753* @private1754*/1755goog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) {1756'use strict';1757var parent = textNode.parentNode;1758if (parent == node) {1759// If textNode is a child of node, then node comes first.1760return -1;1761}1762var sibling = node;1763while (sibling.parentNode != parent) {1764sibling = sibling.parentNode;1765}1766return goog.dom.compareSiblingOrder_(sibling, textNode);1767};176817691770/**1771* Utility function to compare the position of two nodes known to be non-equal1772* siblings.1773* @param {Node} node1 The first node to compare.1774* @param {!Node} node2 The second node to compare.1775* @return {number} -1 if node1 is before node2, +1 otherwise.1776* @private1777*/1778goog.dom.compareSiblingOrder_ = function(node1, node2) {1779'use strict';1780var s = node2;1781while ((s = s.previousSibling)) {1782if (s == node1) {1783// We just found node1 before node2.1784return -1;1785}1786}17871788// Since we didn't find it, node1 must be after node2.1789return 1;1790};179117921793/**1794* Find the deepest common ancestor of the given nodes.1795* @param {...Node} var_args The nodes to find a common ancestor of.1796* @return {Node} The common ancestor of the nodes, or null if there is none.1797* null will only be returned if two or more of the nodes are from different1798* documents.1799*/1800goog.dom.findCommonAncestor = function(var_args) {1801'use strict';1802var i, count = arguments.length;1803if (!count) {1804return null;1805} else if (count == 1) {1806return arguments[0];1807}18081809var paths = [];1810var minLength = Infinity;1811for (i = 0; i < count; i++) {1812// Compute the list of ancestors.1813var ancestors = [];1814var node = arguments[i];1815while (node) {1816ancestors.unshift(node);1817node = node.parentNode;1818}18191820// Save the list for comparison.1821paths.push(ancestors);1822minLength = Math.min(minLength, ancestors.length);1823}1824var output = null;1825for (i = 0; i < minLength; i++) {1826var first = paths[0][i];1827for (var j = 1; j < count; j++) {1828if (first != paths[j][i]) {1829return output;1830}1831}1832output = first;1833}1834return output;1835};183618371838/**1839* Returns whether node is in a document or detached. Throws an error if node1840* itself is a document. This specifically handles two cases beyond naive use of1841* builtins: (1) it works correctly in IE, and (2) it works for elements from1842* different documents/iframes. If neither of these considerations are relevant1843* then a simple `document.contains(node)` may be used instead.1844* @param {!Node} node1845* @return {boolean}1846*/1847goog.dom.isInDocument = function(node) {1848'use strict';1849return (node.ownerDocument.compareDocumentPosition(node) & 16) == 16;1850};185118521853/**1854* Returns the owner document for a node.1855* @param {Node|Window} node The node to get the document for.1856* @return {!Document} The document owning the node.1857*/1858goog.dom.getOwnerDocument = function(node) {1859'use strict';1860// TODO(nnaze): Update param signature to be non-nullable.1861goog.asserts.assert(node, 'Node cannot be null or undefined.');1862return /** @type {!Document} */ (1863node.nodeType == goog.dom.NodeType.DOCUMENT ?1864node :1865node.ownerDocument || node.document);1866};186718681869/**1870* Cross-browser function for getting the document element of a frame or iframe.1871* @param {Element} frame Frame element.1872* @return {!Document} The frame content document.1873*/1874goog.dom.getFrameContentDocument = function(frame) {1875'use strict';1876return frame.contentDocument ||1877/** @type {!HTMLFrameElement} */ (frame).contentWindow.document;1878};187918801881/**1882* Cross-browser function for getting the window of a frame or iframe.1883* @param {Element} frame Frame element.1884* @return {Window} The window associated with the given frame, or null if none1885* exists.1886*/1887goog.dom.getFrameContentWindow = function(frame) {1888'use strict';1889try {1890return frame.contentWindow ||1891(frame.contentDocument ? goog.dom.getWindow(frame.contentDocument) :1892null);1893} catch (e) {1894// NOTE(user): In IE8, checking the contentWindow or contentDocument1895// properties will throw a "Unspecified Error" exception if the iframe is1896// not inserted in the DOM. If we get this we can be sure that no window1897// exists, so return null.1898}1899return null;1900};190119021903/**1904* Sets the text content of a node, with cross-browser support.1905* @param {Node} node The node to change the text content of.1906* @param {string|number} text The value that should replace the node's content.1907* @return {void}1908*/1909goog.dom.setTextContent = function(node, text) {1910'use strict';1911goog.asserts.assert(1912node != null,1913'goog.dom.setTextContent expects a non-null value for node');19141915if ('textContent' in node) {1916node.textContent = text;1917} else if (node.nodeType == goog.dom.NodeType.TEXT) {1918/** @type {!Text} */ (node).data = String(text);1919} else if (1920node.firstChild && node.firstChild.nodeType == goog.dom.NodeType.TEXT) {1921// If the first child is a text node we just change its data and remove the1922// rest of the children.1923while (node.lastChild != node.firstChild) {1924node.removeChild(goog.asserts.assert(node.lastChild));1925}1926/** @type {!Text} */ (node.firstChild).data = String(text);1927} else {1928goog.dom.removeChildren(node);1929var doc = goog.dom.getOwnerDocument(node);1930node.appendChild(doc.createTextNode(String(text)));1931}1932};193319341935/**1936* Gets the outerHTML of a node, which is like innerHTML, except that it1937* actually contains the HTML of the node itself.1938* @param {Element} element The element to get the HTML of.1939* @return {string} The outerHTML of the given element.1940*/1941goog.dom.getOuterHtml = function(element) {1942'use strict';1943goog.asserts.assert(1944element !== null,1945'goog.dom.getOuterHtml expects a non-null value for element');1946// IE, Opera and WebKit all have outerHTML.1947if ('outerHTML' in element) {1948return element.outerHTML;1949} else {1950var doc = goog.dom.getOwnerDocument(element);1951var div = goog.dom.createElement_(doc, goog.dom.TagName.DIV);1952div.appendChild(element.cloneNode(true));1953return div.innerHTML;1954}1955};195619571958/**1959* Finds the first descendant node that matches the filter function, using depth1960* first search. This function offers the most general purpose way of finding a1961* matching element.1962*1963* Prefer using `querySelector` if the matching criteria can be expressed as a1964* CSS selector, or `goog.dom.findElement` if you would filter for `nodeType ==1965* Node.ELEMENT_NODE`.1966*1967* @param {Node} root The root of the tree to search.1968* @param {function(Node) : boolean} p The filter function.1969* @return {Node|undefined} The found node or undefined if none is found.1970*/1971goog.dom.findNode = function(root, p) {1972'use strict';1973var rv = [];1974var found = goog.dom.findNodes_(root, p, rv, true);1975return found ? rv[0] : undefined;1976};197719781979/**1980* Finds all the descendant nodes that match the filter function, using depth1981* first search. This function offers the most general-purpose way1982* of finding a set of matching elements.1983*1984* Prefer using `querySelectorAll` if the matching criteria can be expressed as1985* a CSS selector, or `goog.dom.findElements` if you would filter for1986* `nodeType == Node.ELEMENT_NODE`.1987*1988* @param {Node} root The root of the tree to search.1989* @param {function(Node) : boolean} p The filter function.1990* @return {!Array<!Node>} The found nodes or an empty array if none are found.1991*/1992goog.dom.findNodes = function(root, p) {1993'use strict';1994var rv = [];1995goog.dom.findNodes_(root, p, rv, false);1996return rv;1997};199819992000/**2001* Finds the first or all the descendant nodes that match the filter function,2002* using a depth first search.2003* @param {Node} root The root of the tree to search.2004* @param {function(Node) : boolean} p The filter function.2005* @param {!Array<!Node>} rv The found nodes are added to this array.2006* @param {boolean} findOne If true we exit after the first found node.2007* @return {boolean} Whether the search is complete or not. True in case findOne2008* is true and the node is found. False otherwise.2009* @private2010*/2011goog.dom.findNodes_ = function(root, p, rv, findOne) {2012'use strict';2013if (root != null) {2014var child = root.firstChild;2015while (child) {2016if (p(child)) {2017rv.push(child);2018if (findOne) {2019return true;2020}2021}2022if (goog.dom.findNodes_(child, p, rv, findOne)) {2023return true;2024}2025child = child.nextSibling;2026}2027}2028return false;2029};203020312032/**2033* Finds the first descendant element (excluding `root`) that matches the filter2034* function, using depth first search. Prefer using `querySelector` if the2035* matching criteria can be expressed as a CSS selector.2036*2037* @param {!Element | !Document} root2038* @param {function(!Element): boolean} pred Filter function.2039* @return {?Element} First matching element or null if there is none.2040*/2041goog.dom.findElement = function(root, pred) {2042'use strict';2043var stack = goog.dom.getChildrenReverse_(root);2044while (stack.length > 0) {2045var next = stack.pop();2046if (pred(next)) return next;2047for (var c = next.lastElementChild; c; c = c.previousElementSibling) {2048stack.push(c);2049}2050}2051return null;2052};205320542055/**2056* Finds all the descendant elements (excluding `root`) that match the filter2057* function, using depth first search. Prefer using `querySelectorAll` if the2058* matching criteria can be expressed as a CSS selector.2059*2060* @param {!Element | !Document} root2061* @param {function(!Element): boolean} pred Filter function.2062* @return {!Array<!Element>}2063*/2064goog.dom.findElements = function(root, pred) {2065'use strict';2066var result = [], stack = goog.dom.getChildrenReverse_(root);2067while (stack.length > 0) {2068var next = stack.pop();2069if (pred(next)) result.push(next);2070for (var c = next.lastElementChild; c; c = c.previousElementSibling) {2071stack.push(c);2072}2073}2074return result;2075};207620772078/**2079* @param {!Element | !Document} node2080* @return {!Array<!Element>} node's child elements in reverse order.2081* @private2082*/2083goog.dom.getChildrenReverse_ = function(node) {2084'use strict';2085// document.lastElementChild doesn't exist in IE9; fall back to2086// documentElement.2087if (node.nodeType == goog.dom.NodeType.DOCUMENT) {2088return [node.documentElement];2089} else {2090var children = [];2091for (var c = node.lastElementChild; c; c = c.previousElementSibling) {2092children.push(c);2093}2094return children;2095}2096};209720982099/**2100* Map of tags whose content to ignore when calculating text length.2101* @private {!Object<string, number>}2102* @const2103*/2104goog.dom.TAGS_TO_IGNORE_ = {2105'SCRIPT': 1,2106'STYLE': 1,2107'HEAD': 1,2108'IFRAME': 1,2109'OBJECT': 12110};211121122113/**2114* Map of tags which have predefined values with regard to whitespace.2115* @private {!Object<string, string>}2116* @const2117*/2118goog.dom.PREDEFINED_TAG_VALUES_ = {2119'IMG': ' ',2120'BR': '\n'2121};212221232124/**2125* Returns true if the element has a tab index that allows it to receive2126* keyboard focus (tabIndex >= 0), false otherwise. Note that some elements2127* natively support keyboard focus, even if they have no tab index.2128* @param {!Element} element Element to check.2129* @return {boolean} Whether the element has a tab index that allows keyboard2130* focus.2131*/2132goog.dom.isFocusableTabIndex = function(element) {2133'use strict';2134return goog.dom.hasSpecifiedTabIndex_(element) &&2135goog.dom.isTabIndexFocusable_(element);2136};213721382139/**2140* Enables or disables keyboard focus support on the element via its tab index.2141* Only elements for which {@link goog.dom.isFocusableTabIndex} returns true2142* (or elements that natively support keyboard focus, like form elements) can2143* receive keyboard focus. See http://go/tabindex for more info.2144* @param {Element} element Element whose tab index is to be changed.2145* @param {boolean} enable Whether to set or remove a tab index on the element2146* that supports keyboard focus.2147* @return {void}2148*/2149goog.dom.setFocusableTabIndex = function(element, enable) {2150'use strict';2151if (enable) {2152element.tabIndex = 0;2153} else {2154// Set tabIndex to -1 first, then remove it. This is a workaround for2155// Safari (confirmed in version 4 on Windows). When removing the attribute2156// without setting it to -1 first, the element remains keyboard focusable2157// despite not having a tabIndex attribute anymore.2158element.tabIndex = -1;2159element.removeAttribute('tabIndex'); // Must be camelCase!2160}2161};216221632164/**2165* Returns true if the element can be focused, i.e. it has a tab index that2166* allows it to receive keyboard focus (tabIndex >= 0), or it is an element2167* that natively supports keyboard focus.2168* @param {!Element} element Element to check.2169* @return {boolean} Whether the element allows keyboard focus.2170*/2171goog.dom.isFocusable = function(element) {2172'use strict';2173var focusable;2174// Some elements can have unspecified tab index and still receive focus.2175if (goog.dom.nativelySupportsFocus_(element)) {2176// Make sure the element is not disabled ...2177focusable = !element.disabled &&2178// ... and if a tab index is specified, it allows focus.2179(!goog.dom.hasSpecifiedTabIndex_(element) ||2180goog.dom.isTabIndexFocusable_(element));2181} else {2182focusable = goog.dom.isFocusableTabIndex(element);2183}21842185// IE requires elements to be visible in order to focus them.2186return focusable && goog.userAgent.IE ?2187goog.dom.hasNonZeroBoundingRect_(/** @type {!HTMLElement} */ (element)) :2188focusable;2189};219021912192/**2193* Returns true if the element has a specified tab index.2194* @param {!Element} element Element to check.2195* @return {boolean} Whether the element has a specified tab index.2196* @private2197*/2198goog.dom.hasSpecifiedTabIndex_ = function(element) {2199'use strict';2200return element.hasAttribute('tabindex');2201};220222032204/**2205* Returns true if the element's tab index allows the element to be focused.2206* @param {!Element} element Element to check.2207* @return {boolean} Whether the element's tab index allows focus.2208* @private2209*/2210goog.dom.isTabIndexFocusable_ = function(element) {2211'use strict';2212var index = /** @type {!HTMLElement} */ (element).tabIndex;2213// NOTE: IE9 puts tabIndex in 16-bit int, e.g. -2 is 65534.2214return typeof (index) === 'number' && index >= 0 && index < 32768;2215};221622172218/**2219* Returns true if the element is focusable even when tabIndex is not set.2220* @param {!Element} element Element to check.2221* @return {boolean} Whether the element natively supports focus.2222* @private2223*/2224goog.dom.nativelySupportsFocus_ = function(element) {2225'use strict';2226return (2227element.tagName == goog.dom.TagName.A && element.hasAttribute('href') ||2228element.tagName == goog.dom.TagName.INPUT ||2229element.tagName == goog.dom.TagName.TEXTAREA ||2230element.tagName == goog.dom.TagName.SELECT ||2231element.tagName == goog.dom.TagName.BUTTON);2232};223322342235/**2236* Returns true if the element has a bounding rectangle that would be visible2237* (i.e. its width and height are greater than zero).2238* @param {!HTMLElement} element Element to check.2239* @return {boolean} Whether the element has a non-zero bounding rectangle.2240* @private2241*/2242goog.dom.hasNonZeroBoundingRect_ = function(element) {2243'use strict';2244var rect;2245if (typeof element['getBoundingClientRect'] !== 'function' ||2246// In IE, getBoundingClientRect throws on detached nodes.2247(goog.userAgent.IE && element.parentElement == null)) {2248rect = {'height': element.offsetHeight, 'width': element.offsetWidth};2249} else {2250rect = element.getBoundingClientRect();2251}2252return rect != null && rect.height > 0 && rect.width > 0;2253};225422552256/**2257* Returns the text content of the current node, without markup and invisible2258* symbols. New lines are stripped and whitespace is collapsed,2259* such that each character would be visible.2260*2261* In browsers that support it, innerText is used. Other browsers attempt to2262* simulate it via node traversal. Line breaks are canonicalized in IE.2263*2264* @param {Node} node The node from which we are getting content.2265* @return {string} The text content.2266*/2267goog.dom.getTextContent = function(node) {2268'use strict';2269var textContent;2270var buf = [];2271goog.dom.getTextContent_(node, buf, true);2272textContent = buf.join('');22732274// Strip ­ entities. goog.format.insertWordBreaks inserts them in Opera.2275textContent = textContent.replace(/ \xAD /g, ' ').replace(/\xAD/g, '');2276// Strip ​ entities. goog.format.insertWordBreaks inserts them in IE8.2277textContent = textContent.replace(/\u200B/g, '');22782279textContent = textContent.replace(/ +/g, ' ');2280if (textContent != ' ') {2281textContent = textContent.replace(/^\s*/, '');2282}22832284return textContent;2285};228622872288/**2289* Returns the text content of the current node, without markup.2290*2291* Unlike `getTextContent` this method does not collapse whitespaces2292* or normalize lines breaks.2293*2294* @param {Node} node The node from which we are getting content.2295* @return {string} The raw text content.2296*/2297goog.dom.getRawTextContent = function(node) {2298'use strict';2299var buf = [];2300goog.dom.getTextContent_(node, buf, false);23012302return buf.join('');2303};230423052306/**2307* Recursive support function for text content retrieval.2308*2309* @param {Node} node The node from which we are getting content.2310* @param {Array<string>} buf string buffer.2311* @param {boolean} normalizeWhitespace Whether to normalize whitespace.2312* @private2313*/2314goog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) {2315'use strict';2316if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) {2317// ignore certain tags2318} else if (node.nodeType == goog.dom.NodeType.TEXT) {2319if (normalizeWhitespace) {2320buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, ''));2321} else {2322buf.push(node.nodeValue);2323}2324} else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {2325buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]);2326} else {2327var child = node.firstChild;2328while (child) {2329goog.dom.getTextContent_(child, buf, normalizeWhitespace);2330child = child.nextSibling;2331}2332}2333};233423352336/**2337* Returns the text length of the text contained in a node, without markup. This2338* is equivalent to the selection length if the node was selected, or the number2339* of cursor movements to traverse the node. Images & BRs take one space. New2340* lines are ignored.2341*2342* @param {Node} node The node whose text content length is being calculated.2343* @return {number} The length of `node`'s text content.2344*/2345goog.dom.getNodeTextLength = function(node) {2346'use strict';2347return goog.dom.getTextContent(node).length;2348};234923502351/**2352* Returns the text offset of a node relative to one of its ancestors. The text2353* length is the same as the length calculated by goog.dom.getNodeTextLength.2354*2355* @param {Node} node The node whose offset is being calculated.2356* @param {Node=} opt_offsetParent The node relative to which the offset will2357* be calculated. Defaults to the node's owner document's body.2358* @return {number} The text offset.2359*/2360goog.dom.getNodeTextOffset = function(node, opt_offsetParent) {2361'use strict';2362var root = opt_offsetParent || goog.dom.getOwnerDocument(node).body;2363var buf = [];2364while (node && node != root) {2365var cur = node;2366while ((cur = cur.previousSibling)) {2367buf.unshift(goog.dom.getTextContent(cur));2368}2369node = node.parentNode;2370}2371// Trim left to deal with FF cases when there might be line breaks and empty2372// nodes at the front of the text2373return goog.string.trimLeft(buf.join('')).replace(/ +/g, ' ').length;2374};237523762377/**2378* Returns the node at a given offset in a parent node. If an object is2379* provided for the optional third parameter, the node and the remainder of the2380* offset will stored as properties of this object.2381* @param {Node} parent The parent node.2382* @param {number} offset The offset into the parent node.2383* @param {Object=} opt_result Object to be used to store the return value. The2384* return value will be stored in the form {node: Node, remainder: number}2385* if this object is provided.2386* @return {Node} The node at the given offset.2387*/2388goog.dom.getNodeAtOffset = function(parent, offset, opt_result) {2389'use strict';2390var stack = [parent], pos = 0, cur = null;2391while (stack.length > 0 && pos < offset) {2392cur = stack.pop();2393if (cur.nodeName in goog.dom.TAGS_TO_IGNORE_) {2394// ignore certain tags2395} else if (cur.nodeType == goog.dom.NodeType.TEXT) {2396var text = cur.nodeValue.replace(/(\r\n|\r|\n)/g, '').replace(/ +/g, ' ');2397pos += text.length;2398} else if (cur.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {2399pos += goog.dom.PREDEFINED_TAG_VALUES_[cur.nodeName].length;2400} else {2401for (var i = cur.childNodes.length - 1; i >= 0; i--) {2402stack.push(cur.childNodes[i]);2403}2404}2405}2406if (goog.utils.isObject(opt_result)) {2407opt_result.remainder = cur ? cur.nodeValue.length + offset - pos - 1 : 0;2408opt_result.node = cur;2409}24102411return cur;2412};241324142415/**2416* Returns true if the object is a `NodeList`. To qualify as a NodeList,2417* the object must have a numeric length property and an item function (which2418* has type 'string' on IE for some reason).2419* @param {Object} val Object to test.2420* @return {boolean} Whether the object is a NodeList.2421*/2422goog.dom.isNodeList = function(val) {2423'use strict';2424// TODO(attila): Now the isNodeList is part of goog.dom we can use2425// goog.userAgent to make this simpler.2426// A NodeList must have a length property of type 'number' on all platforms.2427if (val && typeof val.length == 'number') {2428// A NodeList is an object everywhere except Safari, where it's a function.2429if (goog.utils.isObject(val)) {2430// A NodeList must have an item function (on non-IE platforms) or an item2431// property of type 'string' (on IE).2432return typeof val.item == 'function' || typeof val.item == 'string';2433} else if (typeof val === 'function') {2434// On Safari, a NodeList is a function with an item property that is also2435// a function.2436return typeof /** @type {?} */ (val.item) == 'function';2437}2438}24392440// Not a NodeList.2441return false;2442};244324442445/**2446* Walks up the DOM hierarchy returning the first ancestor that has the passed2447* tag name and/or class name. If the passed element matches the specified2448* criteria, the element itself is returned.2449* @param {Node} element The DOM node to start with.2450* @param {?(goog.dom.TagName<T>|string)=} opt_tag The tag name to match (or2451* null/undefined to match only based on class name).2452* @param {?string=} opt_class The class name to match (or null/undefined to2453* match only based on tag name).2454* @param {number=} opt_maxSearchSteps Maximum number of levels to search up the2455* dom.2456* @return {?R} The first ancestor that matches the passed criteria, or2457* null if no match is found. The return type is {?Element} if opt_tag is2458* not a member of goog.dom.TagName or a more specific type if it is (e.g.2459* {?HTMLAnchorElement} for goog.dom.TagName.A).2460* @template T2461* @template R := cond(isUnknown(T), 'Element', T) =:2462*/2463goog.dom.getAncestorByTagNameAndClass = function(2464element, opt_tag, opt_class, opt_maxSearchSteps) {2465'use strict';2466if (!opt_tag && !opt_class) {2467return null;2468}2469var tagName = opt_tag ? String(opt_tag).toUpperCase() : null;2470return /** @type {Element} */ (goog.dom.getAncestor(element, function(node) {2471'use strict';2472return (!tagName || node.nodeName == tagName) &&2473(!opt_class ||2474typeof node.className === 'string' &&2475goog.array.contains(node.className.split(/\s+/), opt_class));2476}, true, opt_maxSearchSteps));2477};247824792480/**2481* Walks up the DOM hierarchy returning the first ancestor that has the passed2482* class name. If the passed element matches the specified criteria, the2483* element itself is returned.2484* @param {Node} element The DOM node to start with.2485* @param {string} className The class name to match.2486* @param {number=} opt_maxSearchSteps Maximum number of levels to search up the2487* dom.2488* @return {Element} The first ancestor that matches the passed criteria, or2489* null if none match.2490*/2491goog.dom.getAncestorByClass = function(element, className, opt_maxSearchSteps) {2492'use strict';2493return goog.dom.getAncestorByTagNameAndClass(2494element, null, className, opt_maxSearchSteps);2495};249624972498/**2499* Walks up the DOM hierarchy returning the first ancestor that passes the2500* matcher function.2501* @param {Node} element The DOM node to start with.2502* @param {function(!Node) : boolean} matcher A function that returns true if2503* the passed node matches the desired criteria.2504* @param {boolean=} opt_includeNode If true, the node itself is included in2505* the search (the first call to the matcher will pass startElement as2506* the node to test).2507* @param {number=} opt_maxSearchSteps Maximum number of levels to search up the2508* dom.2509* @return {Node} DOM node that matched the matcher, or null if there was2510* no match.2511*/2512goog.dom.getAncestor = function(2513element, matcher, opt_includeNode, opt_maxSearchSteps) {2514'use strict';2515if (element && !opt_includeNode) {2516element = element.parentNode;2517}2518var steps = 0;2519while (element &&2520(opt_maxSearchSteps == null || steps <= opt_maxSearchSteps)) {2521goog.asserts.assert(element.name != 'parentNode');2522if (matcher(element)) {2523return element;2524}2525element = element.parentNode;2526steps++;2527}2528// Reached the root of the DOM without a match2529return null;2530};253125322533/**2534* Determines the active element in the given document.2535* @param {Document} doc The document to look in.2536* @return {Element} The active element.2537*/2538goog.dom.getActiveElement = function(doc) {2539'use strict';2540// While in an iframe, IE9 will throw "Unspecified error" when accessing2541// activeElement.2542try {2543var activeElement = doc && doc.activeElement;2544// While not in an iframe, IE9-11 sometimes gives null.2545// While in an iframe, IE11 sometimes returns an empty object.2546return activeElement && activeElement.nodeName ? activeElement : null;2547} catch (e) {2548return null;2549}2550};255125522553/**2554* Gives the current devicePixelRatio.2555*2556* By default, this is the value of window.devicePixelRatio (which should be2557* preferred if present).2558*2559* If window.devicePixelRatio is not present, the ratio is calculated with2560* window.matchMedia, if present. Otherwise, gives 1.0.2561*2562* Some browsers (including Chrome) consider the browser zoom level in the pixel2563* ratio, so the value may change across multiple calls.2564*2565* @return {number} The number of actual pixels per virtual pixel.2566*/2567goog.dom.getPixelRatio = function() {2568'use strict';2569var win = goog.dom.getWindow();2570if (win.devicePixelRatio !== undefined) {2571return win.devicePixelRatio;2572} else if (win.matchMedia) {2573// Should be for IE10 and FF6-17 (this basically clamps to lower)2574// Note that the order of these statements is important2575return goog.dom.matchesPixelRatio_(3) || goog.dom.matchesPixelRatio_(2) ||2576goog.dom.matchesPixelRatio_(1.5) || goog.dom.matchesPixelRatio_(1) ||2577.75;2578}2579return 1;2580};258125822583/**2584* Calculates a mediaQuery to check if the current device supports the2585* given actual to virtual pixel ratio.2586* @param {number} pixelRatio The ratio of actual pixels to virtual pixels.2587* @return {number} pixelRatio if applicable, otherwise 0.2588* @private2589*/2590goog.dom.matchesPixelRatio_ = function(pixelRatio) {2591'use strict';2592var win = goog.dom.getWindow();2593/**2594* Due to the 1:96 fixed ratio of CSS in to CSS px, 1dppx is equivalent to2595* 96dpi.2596* @const {number}2597*/2598var dpiPerDppx = 96;2599var query =2600// FF16-172601'(min-resolution: ' + pixelRatio + 'dppx),' +2602// FF6-152603'(min--moz-device-pixel-ratio: ' + pixelRatio + '),' +2604// IE10 (this works for the two browsers above too but I don't want to2605// trust the 1:96 fixed ratio magic)2606'(min-resolution: ' + (pixelRatio * dpiPerDppx) + 'dpi)';2607return win.matchMedia(query).matches ? pixelRatio : 0;2608};260926102611/**2612* Gets '2d' context of a canvas. Shortcut for canvas.getContext('2d') with a2613* type information.2614* @param {!HTMLCanvasElement|!OffscreenCanvas} canvas2615* @return {!CanvasRenderingContext2D}2616*/2617goog.dom.getCanvasContext2D = function(canvas) {2618'use strict';2619return /** @type {!CanvasRenderingContext2D} */ (canvas.getContext('2d'));2620};2621262226232624/**2625* Create an instance of a DOM helper with a new document object.2626* @param {Document=} opt_document Document object to associate with this2627* DOM helper.2628* @constructor2629*/2630goog.dom.DomHelper = function(opt_document) {2631'use strict';2632/**2633* Reference to the document object to use2634* @type {!Document}2635* @private2636*/2637this.document_ = opt_document || goog.global.document || document;2638};263926402641/**2642* Gets the dom helper object for the document where the element resides.2643* @param {Node=} opt_node If present, gets the DomHelper for this node.2644* @return {!goog.dom.DomHelper} The DomHelper.2645*/2646goog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper;264726482649/**2650* Sets the document object.2651* @param {!Document} document Document object.2652*/2653goog.dom.DomHelper.prototype.setDocument = function(document) {2654'use strict';2655this.document_ = document;2656};265726582659/**2660* Gets the document object being used by the dom library.2661* @return {!Document} Document object.2662*/2663goog.dom.DomHelper.prototype.getDocument = function() {2664'use strict';2665return this.document_;2666};266726682669/**2670* Alias for `getElementById`. If a DOM node is passed in then we just2671* return that.2672* @param {string|Element} element Element ID or a DOM node.2673* @return {Element} The element with the given ID, or the node passed in.2674*/2675goog.dom.DomHelper.prototype.getElement = function(element) {2676'use strict';2677return goog.dom.getElementHelper_(this.document_, element);2678};267926802681/**2682* Gets an element by id, asserting that the element is found.2683*2684* This is used when an element is expected to exist, and should fail with2685* an assertion error if it does not (if assertions are enabled).2686*2687* @param {string} id Element ID.2688* @return {!Element} The element with the given ID, if it exists.2689*/2690goog.dom.DomHelper.prototype.getRequiredElement = function(id) {2691'use strict';2692return goog.dom.getRequiredElementHelper_(this.document_, id);2693};269426952696/**2697* Alias for `getElement`.2698* @param {string|Element} element Element ID or a DOM node.2699* @return {Element} The element with the given ID, or the node passed in.2700* @deprecated Use {@link goog.dom.DomHelper.prototype.getElement} instead.2701*/2702goog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement;270327042705/**2706* Gets elements by tag name.2707* @param {!goog.dom.TagName<T>} tagName2708* @param {(!Document|!Element)=} opt_parent Parent element or document where to2709* look for elements. Defaults to document of this DomHelper.2710* @return {!NodeList<R>} List of elements. The members of the list are2711* {!Element} if tagName is not a member of goog.dom.TagName or more2712* specific types if it is (e.g. {!HTMLAnchorElement} for2713* goog.dom.TagName.A).2714* @template T2715* @template R := cond(isUnknown(T), 'Element', T) =:2716*/2717goog.dom.DomHelper.prototype.getElementsByTagName = function(2718tagName, opt_parent) {2719'use strict';2720var parent = opt_parent || this.document_;2721return parent.getElementsByTagName(String(tagName));2722};272327242725/**2726* Looks up elements by both tag and class name, using browser native functions2727* (`querySelectorAll`, `getElementsByTagName` or2728* `getElementsByClassName`) where possible. The returned array is a live2729* NodeList or a static list depending on the code path taken.2730*2731* @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name or * for all2732* tags.2733* @param {?string=} opt_class Optional class name.2734* @param {(Document|Element)=} opt_el Optional element to look in.2735* @return {!IArrayLike<R>} Array-like list of elements (only a length property2736* and numerical indices are guaranteed to exist). The members of the array2737* are {!Element} if opt_tag is not a member of goog.dom.TagName or more2738* specific types if it is (e.g. {!HTMLAnchorElement} for2739* goog.dom.TagName.A).2740* @template T2741* @template R := cond(isUnknown(T), 'Element', T) =:2742*/2743goog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(2744opt_tag, opt_class, opt_el) {2745'use strict';2746return goog.dom.getElementsByTagNameAndClass_(2747this.document_, opt_tag, opt_class, opt_el);2748};274927502751/**2752* Gets the first element matching the tag and the class.2753*2754* @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.2755* @param {?string=} opt_class Optional class name.2756* @param {(Document|Element)=} opt_el Optional element to look in.2757* @return {?R} Reference to a DOM node. The return type is {?Element} if2758* tagName is a string or a more specific type if it is a member of2759* goog.dom.TagName (e.g. {?HTMLAnchorElement} for goog.dom.TagName.A).2760* @template T2761* @template R := cond(isUnknown(T), 'Element', T) =:2762*/2763goog.dom.DomHelper.prototype.getElementByTagNameAndClass = function(2764opt_tag, opt_class, opt_el) {2765'use strict';2766return goog.dom.getElementByTagNameAndClass_(2767this.document_, opt_tag, opt_class, opt_el);2768};276927702771/**2772* Returns an array of all the elements with the provided className.2773* @param {string} className the name of the class to look for.2774* @param {Element|Document=} opt_el Optional element to look in.2775* @return {!IArrayLike<!Element>} The items found with the class name provided.2776*/2777goog.dom.DomHelper.prototype.getElementsByClass = function(className, opt_el) {2778'use strict';2779var doc = opt_el || this.document_;2780return goog.dom.getElementsByClass(className, doc);2781};278227832784/**2785* Returns the first element we find matching the provided class name.2786* @param {string} className the name of the class to look for.2787* @param {(Element|Document)=} opt_el Optional element to look in.2788* @return {Element} The first item found with the class name provided.2789*/2790goog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) {2791'use strict';2792var doc = opt_el || this.document_;2793return goog.dom.getElementByClass(className, doc);2794};279527962797/**2798* Ensures an element with the given className exists, and then returns the2799* first element with the provided className.2800* @param {string} className the name of the class to look for.2801* @param {(!Element|!Document)=} opt_root Optional element or document to look2802* in.2803* @return {!Element} The first item found with the class name provided.2804* @throws {goog.asserts.AssertionError} Thrown if no element is found.2805*/2806goog.dom.DomHelper.prototype.getRequiredElementByClass = function(2807className, opt_root) {2808'use strict';2809var root = opt_root || this.document_;2810return goog.dom.getRequiredElementByClass(className, root);2811};281228132814/**2815* Alias for `getElementsByTagNameAndClass`.2816* @deprecated Use DomHelper getElementsByTagNameAndClass.2817*2818* @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.2819* @param {?string=} opt_class Optional class name.2820* @param {Element=} opt_el Optional element to look in.2821* @return {!IArrayLike<R>} Array-like list of elements (only a length property2822* and numerical indices are guaranteed to exist). The members of the array2823* are {!Element} if opt_tag is a string or more specific types if it is2824* a member of goog.dom.TagName (e.g. {!HTMLAnchorElement} for2825* goog.dom.TagName.A).2826* @template T2827* @template R := cond(isUnknown(T), 'Element', T) =:2828*/2829goog.dom.DomHelper.prototype.$$ =2830goog.dom.DomHelper.prototype.getElementsByTagNameAndClass;283128322833/**2834* Sets a number of properties on a node.2835* @param {Element} element DOM node to set properties on.2836* @param {Object} properties Hash of property:value pairs.2837*/2838goog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties;283928402841/**2842* Gets the dimensions of the viewport.2843* @param {Window=} opt_window Optional window element to test. Defaults to2844* the window of the Dom Helper.2845* @return {!goog.math.Size} Object with values 'width' and 'height'.2846*/2847goog.dom.DomHelper.prototype.getViewportSize = function(opt_window) {2848'use strict';2849// TODO(arv): This should not take an argument. That breaks the rule of a2850// a DomHelper representing a single frame/window/document.2851return goog.dom.getViewportSize(opt_window || this.getWindow());2852};285328542855/**2856* Calculates the height of the document.2857*2858* @return {number} The height of the document.2859*/2860goog.dom.DomHelper.prototype.getDocumentHeight = function() {2861'use strict';2862return goog.dom.getDocumentHeight_(this.getWindow());2863};286428652866/**2867* Typedef for use with goog.dom.createDom and goog.dom.append.2868* @typedef {Object|string|Array|NodeList}2869*/2870goog.dom.Appendable;287128722873/**2874* Returns a dom node with a set of attributes. This function accepts varargs2875* for subsequent nodes to be added. Subsequent nodes will be added to the2876* first node as childNodes.2877*2878* So:2879* <code>createDom(goog.dom.TagName.DIV, null, createDom(goog.dom.TagName.P),2880* createDom(goog.dom.TagName.P));</code> would return a div with two child2881* paragraphs2882*2883* An easy way to move all child nodes of an existing element to a new parent2884* element is:2885* <code>createDom(goog.dom.TagName.DIV, null, oldElement.childNodes);</code>2886* which will remove all child nodes from the old element and add them as2887* child nodes of the new DIV.2888*2889* @param {string|!goog.dom.TagName<T>} tagName Tag to create.2890* @param {?Object|?Array<string>|string=} opt_attributes If object, then a map2891* of name-value pairs for attributes. If a string, then this is the2892* className of the new element. If an array, the elements will be joined2893* together as the className of the new element.2894* @param {...(goog.dom.Appendable|undefined)} var_args Further DOM nodes or2895* strings for text nodes. If one of the var_args is an array or2896* NodeList, its elements will be added as childNodes instead.2897* @return {R} Reference to a DOM node. The return type is {!Element} if tagName2898* is a string or a more specific type if it is a member of2899* goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).2900* @template T2901* @template R := cond(isUnknown(T), 'Element', T) =:2902*/2903goog.dom.DomHelper.prototype.createDom = function(2904tagName, opt_attributes, var_args) {2905'use strict';2906return goog.dom.createDom_(this.document_, arguments);2907};290829092910/**2911* Alias for `createDom`.2912* @param {string|!goog.dom.TagName<T>} tagName Tag to create.2913* @param {?Object|?Array<string>|string=} opt_attributes If object, then a map2914* of name-value pairs for attributes. If a string, then this is the2915* className of the new element. If an array, the elements will be joined2916* together as the className of the new element.2917* @param {...(goog.dom.Appendable|undefined)} var_args Further DOM nodes or2918* strings for text nodes. If one of the var_args is an array, its children2919* will be added as childNodes instead.2920* @return {R} Reference to a DOM node. The return type is {!Element} if tagName2921* is a string or a more specific type if it is a member of2922* goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).2923* @template T2924* @template R := cond(isUnknown(T), 'Element', T) =:2925* @deprecated Use {@link goog.dom.DomHelper.prototype.createDom} instead.2926*/2927goog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom;292829292930/**2931* Creates a new element.2932* @param {string|!goog.dom.TagName<T>} name Tag to create.2933* @return {R} The new element. The return type is {!Element} if name is2934* a string or a more specific type if it is a member of goog.dom.TagName2935* (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).2936* @template T2937* @template R := cond(isUnknown(T), 'Element', T) =:2938*/2939goog.dom.DomHelper.prototype.createElement = function(name) {2940'use strict';2941return goog.dom.createElement_(this.document_, name);2942};294329442945/**2946* Creates a new text node.2947* @param {number|string} content Content.2948* @return {!Text} The new text node.2949*/2950goog.dom.DomHelper.prototype.createTextNode = function(content) {2951'use strict';2952return this.document_.createTextNode(String(content));2953};295429552956/**2957* Create a table.2958* @param {number} rows The number of rows in the table. Must be >= 1.2959* @param {number} columns The number of columns in the table. Must be >= 1.2960* @param {boolean=} opt_fillWithNbsp If true, fills table entries with2961* `goog.string.Unicode.NBSP` characters.2962* @return {!HTMLElement} The created table.2963*/2964goog.dom.DomHelper.prototype.createTable = function(2965rows, columns, opt_fillWithNbsp) {2966'use strict';2967return goog.dom.createTable_(2968this.document_, rows, columns, !!opt_fillWithNbsp);2969};297029712972/**2973* Converts an HTML into a node or a document fragment. A single Node is used if2974* `html` only generates a single node. If `html` generates multiple2975* nodes then these are put inside a `DocumentFragment`. This is a safe2976* version of `goog.dom.DomHelper#htmlToDocumentFragment` which is now2977* deleted.2978* @param {!goog.html.SafeHtml} html The HTML markup to convert.2979* @return {!Node} The resulting node.2980*/2981goog.dom.DomHelper.prototype.safeHtmlToNode = function(html) {2982'use strict';2983return goog.dom.safeHtmlToNode_(this.document_, html);2984};298529862987/**2988* Returns true if the browser is in "CSS1-compatible" (standards-compliant)2989* mode, false otherwise.2990* @return {boolean} True if in CSS1-compatible mode.2991*/2992goog.dom.DomHelper.prototype.isCss1CompatMode = function() {2993'use strict';2994return goog.dom.isCss1CompatMode_(this.document_);2995};299629972998/**2999* Gets the window object associated with the document.3000* @return {!Window} The window associated with the given document.3001*/3002goog.dom.DomHelper.prototype.getWindow = function() {3003'use strict';3004return goog.dom.getWindow_(this.document_);3005};300630073008/**3009* Gets the document scroll element.3010* @return {!Element} Scrolling element.3011*/3012goog.dom.DomHelper.prototype.getDocumentScrollElement = function() {3013'use strict';3014return goog.dom.getDocumentScrollElement_(this.document_);3015};301630173018/**3019* Gets the document scroll distance as a coordinate object.3020* @return {!goog.math.Coordinate} Object with properties 'x' and 'y'.3021*/3022goog.dom.DomHelper.prototype.getDocumentScroll = function() {3023'use strict';3024return goog.dom.getDocumentScroll_(this.document_);3025};302630273028/**3029* Determines the active element in the given document.3030* @param {Document=} opt_doc The document to look in.3031* @return {Element} The active element.3032*/3033goog.dom.DomHelper.prototype.getActiveElement = function(opt_doc) {3034'use strict';3035return goog.dom.getActiveElement(opt_doc || this.document_);3036};303730383039/**3040* Appends a child to a node.3041* @param {Node} parent Parent.3042* @param {Node} child Child.3043*/3044goog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild;304530463047/**3048* Appends a node with text or other nodes.3049* @param {!Node} parent The node to append nodes to.3050* @param {...goog.dom.Appendable} var_args The things to append to the node.3051* If this is a Node it is appended as is.3052* If this is a string then a text node is appended.3053* If this is an array like object then fields 0 to length - 1 are appended.3054*/3055goog.dom.DomHelper.prototype.append = goog.dom.append;305630573058/**3059* Determines if the given node can contain children, intended to be used for3060* HTML generation.3061*3062* @param {Node} node The node to check.3063* @return {boolean} Whether the node can contain children.3064*/3065goog.dom.DomHelper.prototype.canHaveChildren = goog.dom.canHaveChildren;306630673068/**3069* Removes all the child nodes on a DOM node.3070* @param {Node} node Node to remove children from.3071*/3072goog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren;307330743075/**3076* Inserts a new node before an existing reference node (i.e., as the previous3077* sibling). If the reference node has no parent, then does nothing.3078* @param {Node} newNode Node to insert.3079* @param {Node} refNode Reference node to insert before.3080*/3081goog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore;308230833084/**3085* Inserts a new node after an existing reference node (i.e., as the next3086* sibling). If the reference node has no parent, then does nothing.3087* @param {Node} newNode Node to insert.3088* @param {Node} refNode Reference node to insert after.3089*/3090goog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter;309130923093/**3094* Insert a child at a given index. If index is larger than the number of child3095* nodes that the parent currently has, the node is inserted as the last child3096* node.3097* @param {Element} parent The element into which to insert the child.3098* @param {Node} child The element to insert.3099* @param {number} index The index at which to insert the new child node. Must3100* not be negative.3101*/3102goog.dom.DomHelper.prototype.insertChildAt = goog.dom.insertChildAt;310331043105/**3106* Removes a node from its parent.3107* @param {Node} node The node to remove.3108* @return {Node} The node removed if removed; else, null.3109*/3110goog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode;311131123113/**3114* Replaces a node in the DOM tree. Will do nothing if `oldNode` has no3115* parent.3116* @param {Node} newNode Node to insert.3117* @param {Node} oldNode Node to replace.3118*/3119goog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode;312031213122/**3123* Replaces child nodes of `target` with child nodes of `source`. This is3124* roughly equivalent to `target.innerHTML = source.innerHTML` which is not3125* compatible with Trusted Types.3126* @param {?Node} target Node to clean and replace its children.3127* @param {?Node} source Node to get the children from. The nodes will be cloned3128* so they will stay in source.3129*/3130goog.dom.DomHelper.prototype.copyContents = goog.dom.copyContents;313131323133/**3134* Flattens an element. That is, removes it and replace it with its children.3135* @param {Element} element The element to flatten.3136* @return {Element|undefined} The original element, detached from the document3137* tree, sans children, or undefined if the element was already not in the3138* document.3139*/3140goog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement;314131423143/**3144* Returns an array containing just the element children of the given element.3145* @param {Element} element The element whose element children we want.3146* @return {!(Array<!Element>|NodeList<!Element>)} An array or array-like list3147* of just the element children of the given element.3148*/3149goog.dom.DomHelper.prototype.getChildren = goog.dom.getChildren;315031513152/**3153* Returns the first child node that is an element.3154* @param {Node} node The node to get the first child element of.3155* @return {Element} The first child node of `node` that is an element.3156*/3157goog.dom.DomHelper.prototype.getFirstElementChild =3158goog.dom.getFirstElementChild;315931603161/**3162* Returns the last child node that is an element.3163* @param {Node} node The node to get the last child element of.3164* @return {Element} The last child node of `node` that is an element.3165*/3166goog.dom.DomHelper.prototype.getLastElementChild = goog.dom.getLastElementChild;316731683169/**3170* Returns the first next sibling that is an element.3171* @param {Node} node The node to get the next sibling element of.3172* @return {Element} The next sibling of `node` that is an element.3173*/3174goog.dom.DomHelper.prototype.getNextElementSibling =3175goog.dom.getNextElementSibling;317631773178/**3179* Returns the first previous sibling that is an element.3180* @param {Node} node The node to get the previous sibling element of.3181* @return {Element} The first previous sibling of `node` that is3182* an element.3183*/3184goog.dom.DomHelper.prototype.getPreviousElementSibling =3185goog.dom.getPreviousElementSibling;318631873188/**3189* Returns the next node in source order from the given node.3190* @param {Node} node The node.3191* @return {Node} The next node in the DOM tree, or null if this was the last3192* node.3193*/3194goog.dom.DomHelper.prototype.getNextNode = goog.dom.getNextNode;319531963197/**3198* Returns the previous node in source order from the given node.3199* @param {Node} node The node.3200* @return {Node} The previous node in the DOM tree, or null if this was the3201* first node.3202*/3203goog.dom.DomHelper.prototype.getPreviousNode = goog.dom.getPreviousNode;320432053206/**3207* Whether the object looks like a DOM node.3208* @param {?} obj The object being tested for node likeness.3209* @return {boolean} Whether the object looks like a DOM node.3210*/3211goog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike;321232133214/**3215* Whether the object looks like an Element.3216* @param {?} obj The object being tested for Element likeness.3217* @return {boolean} Whether the object looks like an Element.3218*/3219goog.dom.DomHelper.prototype.isElement = goog.dom.isElement;322032213222/**3223* Returns true if the specified value is a Window object. This includes the3224* global window for HTML pages, and iframe windows.3225* @param {?} obj Variable to test.3226* @return {boolean} Whether the variable is a window.3227*/3228goog.dom.DomHelper.prototype.isWindow = goog.dom.isWindow;322932303231/**3232* Returns an element's parent, if it's an Element.3233* @param {Element} element The DOM element.3234* @return {Element} The parent, or null if not an Element.3235*/3236goog.dom.DomHelper.prototype.getParentElement = goog.dom.getParentElement;323732383239/**3240* Whether a node contains another node.3241* @param {Node} parent The node that should contain the other node.3242* @param {Node} descendant The node to test presence of.3243* @return {boolean} Whether the parent node contains the descendant node.3244*/3245goog.dom.DomHelper.prototype.contains = goog.dom.contains;324632473248/**3249* Compares the document order of two nodes, returning 0 if they are the same3250* node, a negative number if node1 is before node2, and a positive number if3251* node2 is before node1. Note that we compare the order the tags appear in the3252* document so in the tree <b><i>text</i></b> the B node is considered to be3253* before the I node.3254*3255* @param {Node} node1 The first node to compare.3256* @param {Node} node2 The second node to compare.3257* @return {number} 0 if the nodes are the same node, a negative number if node13258* is before node2, and a positive number if node2 is before node1.3259*/3260goog.dom.DomHelper.prototype.compareNodeOrder = goog.dom.compareNodeOrder;326132623263/**3264* Find the deepest common ancestor of the given nodes.3265* @param {...Node} var_args The nodes to find a common ancestor of.3266* @return {Node} The common ancestor of the nodes, or null if there is none.3267* null will only be returned if two or more of the nodes are from different3268* documents.3269*/3270goog.dom.DomHelper.prototype.findCommonAncestor = goog.dom.findCommonAncestor;327132723273/**3274* Returns the owner document for a node.3275* @param {Node} node The node to get the document for.3276* @return {!Document} The document owning the node.3277*/3278goog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument;327932803281/**3282* Cross browser function for getting the document element of an iframe.3283* @param {Element} iframe Iframe element.3284* @return {!Document} The frame content document.3285*/3286goog.dom.DomHelper.prototype.getFrameContentDocument =3287goog.dom.getFrameContentDocument;328832893290/**3291* Cross browser function for getting the window of a frame or iframe.3292* @param {Element} frame Frame element.3293* @return {Window} The window associated with the given frame.3294*/3295goog.dom.DomHelper.prototype.getFrameContentWindow =3296goog.dom.getFrameContentWindow;329732983299/**3300* Sets the text content of a node, with cross-browser support.3301* @param {Node} node The node to change the text content of.3302* @param {string|number} text The value that should replace the node's content.3303*/3304goog.dom.DomHelper.prototype.setTextContent = goog.dom.setTextContent;330533063307/**3308* Gets the outerHTML of a node, which islike innerHTML, except that it3309* actually contains the HTML of the node itself.3310* @param {Element} element The element to get the HTML of.3311* @return {string} The outerHTML of the given element.3312*/3313goog.dom.DomHelper.prototype.getOuterHtml = goog.dom.getOuterHtml;331433153316/**3317* Finds the first descendant node that matches the filter function. This does3318* a depth first search.3319* @param {Node} root The root of the tree to search.3320* @param {function(Node) : boolean} p The filter function.3321* @return {Node|undefined} The found node or undefined if none is found.3322*/3323goog.dom.DomHelper.prototype.findNode = goog.dom.findNode;332433253326/**3327* Finds all the descendant nodes that matches the filter function. This does a3328* depth first search.3329* @param {Node} root The root of the tree to search.3330* @param {function(Node) : boolean} p The filter function.3331* @return {Array<Node>} The found nodes or an empty array if none are found.3332*/3333goog.dom.DomHelper.prototype.findNodes = goog.dom.findNodes;333433353336/**3337* Returns true if the element has a tab index that allows it to receive3338* keyboard focus (tabIndex >= 0), false otherwise. Note that some elements3339* natively support keyboard focus, even if they have no tab index.3340* @param {!Element} element Element to check.3341* @return {boolean} Whether the element has a tab index that allows keyboard3342* focus.3343*/3344goog.dom.DomHelper.prototype.isFocusableTabIndex = goog.dom.isFocusableTabIndex;334533463347/**3348* Enables or disables keyboard focus support on the element via its tab index.3349* Only elements for which {@link goog.dom.isFocusableTabIndex} returns true3350* (or elements that natively support keyboard focus, like form elements) can3351* receive keyboard focus. See http://go/tabindex for more info.3352* @param {Element} element Element whose tab index is to be changed.3353* @param {boolean} enable Whether to set or remove a tab index on the element3354* that supports keyboard focus.3355*/3356goog.dom.DomHelper.prototype.setFocusableTabIndex =3357goog.dom.setFocusableTabIndex;335833593360/**3361* Returns true if the element can be focused, i.e. it has a tab index that3362* allows it to receive keyboard focus (tabIndex >= 0), or it is an element3363* that natively supports keyboard focus.3364* @param {!Element} element Element to check.3365* @return {boolean} Whether the element allows keyboard focus.3366*/3367goog.dom.DomHelper.prototype.isFocusable = goog.dom.isFocusable;336833693370/**3371* Returns the text contents of the current node, without markup. New lines are3372* stripped and whitespace is collapsed, such that each character would be3373* visible.3374*3375* In browsers that support it, innerText is used. Other browsers attempt to3376* simulate it via node traversal. Line breaks are canonicalized in IE.3377*3378* @param {Node} node The node from which we are getting content.3379* @return {string} The text content.3380*/3381goog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent;338233833384/**3385* Returns the text length of the text contained in a node, without markup. This3386* is equivalent to the selection length if the node was selected, or the number3387* of cursor movements to traverse the node. Images & BRs take one space. New3388* lines are ignored.3389*3390* @param {Node} node The node whose text content length is being calculated.3391* @return {number} The length of `node`'s text content.3392*/3393goog.dom.DomHelper.prototype.getNodeTextLength = goog.dom.getNodeTextLength;339433953396/**3397* Returns the text offset of a node relative to one of its ancestors. The text3398* length is the same as the length calculated by3399* `goog.dom.getNodeTextLength`.3400*3401* @param {Node} node The node whose offset is being calculated.3402* @param {Node=} opt_offsetParent Defaults to the node's owner document's body.3403* @return {number} The text offset.3404*/3405goog.dom.DomHelper.prototype.getNodeTextOffset = goog.dom.getNodeTextOffset;340634073408/**3409* Returns the node at a given offset in a parent node. If an object is3410* provided for the optional third parameter, the node and the remainder of the3411* offset will stored as properties of this object.3412* @param {Node} parent The parent node.3413* @param {number} offset The offset into the parent node.3414* @param {Object=} opt_result Object to be used to store the return value. The3415* return value will be stored in the form {node: Node, remainder: number}3416* if this object is provided.3417* @return {Node} The node at the given offset.3418*/3419goog.dom.DomHelper.prototype.getNodeAtOffset = goog.dom.getNodeAtOffset;342034213422/**3423* Returns true if the object is a `NodeList`. To qualify as a NodeList,3424* the object must have a numeric length property and an item function (which3425* has type 'string' on IE for some reason).3426* @param {Object} val Object to test.3427* @return {boolean} Whether the object is a NodeList.3428*/3429goog.dom.DomHelper.prototype.isNodeList = goog.dom.isNodeList;343034313432/**3433* Walks up the DOM hierarchy returning the first ancestor that has the passed3434* tag name and/or class name. If the passed element matches the specified3435* criteria, the element itself is returned.3436* @param {Node} element The DOM node to start with.3437* @param {?(goog.dom.TagName<T>|string)=} opt_tag The tag name to match (or3438* null/undefined to match only based on class name).3439* @param {?string=} opt_class The class name to match (or null/undefined to3440* match only based on tag name).3441* @param {number=} opt_maxSearchSteps Maximum number of levels to search up the3442* dom.3443* @return {?R} The first ancestor that matches the passed criteria, or3444* null if no match is found. The return type is {?Element} if opt_tag is3445* not a member of goog.dom.TagName or a more specific type if it is (e.g.3446* {?HTMLAnchorElement} for goog.dom.TagName.A).3447* @template T3448* @template R := cond(isUnknown(T), 'Element', T) =:3449*/3450goog.dom.DomHelper.prototype.getAncestorByTagNameAndClass =3451goog.dom.getAncestorByTagNameAndClass;345234533454/**3455* Walks up the DOM hierarchy returning the first ancestor that has the passed3456* class name. If the passed element matches the specified criteria, the3457* element itself is returned.3458* @param {Node} element The DOM node to start with.3459* @param {string} class The class name to match.3460* @param {number=} opt_maxSearchSteps Maximum number of levels to search up the3461* dom.3462* @return {Element} The first ancestor that matches the passed criteria, or3463* null if none match.3464*/3465goog.dom.DomHelper.prototype.getAncestorByClass = goog.dom.getAncestorByClass;346634673468/**3469* Walks up the DOM hierarchy returning the first ancestor that passes the3470* matcher function.3471* @param {Node} element The DOM node to start with.3472* @param {function(Node) : boolean} matcher A function that returns true if the3473* passed node matches the desired criteria.3474* @param {boolean=} opt_includeNode If true, the node itself is included in3475* the search (the first call to the matcher will pass startElement as3476* the node to test).3477* @param {number=} opt_maxSearchSteps Maximum number of levels to search up the3478* dom.3479* @return {Node} DOM node that matched the matcher, or null if there was3480* no match.3481*/3482goog.dom.DomHelper.prototype.getAncestor = goog.dom.getAncestor;348334843485/**3486* Gets '2d' context of a canvas. Shortcut for canvas.getContext('2d') with a3487* type information.3488* @param {!HTMLCanvasElement} canvas3489* @return {!CanvasRenderingContext2D}3490*/3491goog.dom.DomHelper.prototype.getCanvasContext2D = goog.dom.getCanvasContext2D;349234933494