Debian Codegraph @

closure-library/closure/goog/dom/dom.js

raw
1 // Copyright 2006 The Closure Library Authors. All Rights Reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS-IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 /**
16 * @fileoverview Utilities for manipulating the browser's Document Object Model
17 * Inspiration taken *heavily* from mochikit (http://mochikit.com/).
18 *
19 * You can use {@link goog.dom.DomHelper} to create new dom helpers that refer
20 * to a different document object. This is useful if you are working with
21 * frames or multiple windows.
22 *
23 * @author [email protected] (Erik Arvidsson)
24 */
25
26
27 // TODO(arv): Rename/refactor getTextContent and getRawTextContent. The problem
28 // is that getTextContent should mimic the DOM3 textContent. We should add a
29 // getInnerText (or getText) which tries to return the visible text, innerText.
30
31
32 goog.provide('goog.dom');
33 goog.provide('goog.dom.Appendable');
34 goog.provide('goog.dom.DomHelper');
35
36 goog.require('goog.array');
37 goog.require('goog.asserts');
38 goog.require('goog.dom.BrowserFeature');
39 goog.require('goog.dom.NodeType');
40 goog.require('goog.dom.TagName');
41 goog.require('goog.dom.safe');
42 goog.require('goog.html.SafeHtml');
43 goog.require('goog.html.uncheckedconversions');
44 goog.require('goog.math.Coordinate');
45 goog.require('goog.math.Size');
46 goog.require('goog.object');
47 goog.require('goog.string');
48 goog.require('goog.string.Unicode');
49 goog.require('goog.userAgent');
50
51
52 /**
53 * @define {boolean} Whether we know at compile time that the browser is in
54 * quirks mode.
55 */
56 goog.define('goog.dom.ASSUME_QUIRKS_MODE', false);
57
58
59 /**
60 * @define {boolean} Whether we know at compile time that the browser is in
61 * standards compliance mode.
62 */
63 goog.define('goog.dom.ASSUME_STANDARDS_MODE', false);
64
65
66 /**
67 * Whether we know the compatibility mode at compile time.
68 * @type {boolean}
69 * @private
70 */
71 goog.dom.COMPAT_MODE_KNOWN_ =
72 goog.dom.ASSUME_QUIRKS_MODE || goog.dom.ASSUME_STANDARDS_MODE;
73
74
75 /**
76 * Gets the DomHelper object for the document where the element resides.
77 * @param {(Node|Window)=} opt_element If present, gets the DomHelper for this
78 * element.
79 * @return {!goog.dom.DomHelper} The DomHelper.
80 */
81 goog.dom.getDomHelper = function(opt_element) {
82 return opt_element ?
83 new goog.dom.DomHelper(goog.dom.getOwnerDocument(opt_element)) :
84 (goog.dom.defaultDomHelper_ ||
85 (goog.dom.defaultDomHelper_ = new goog.dom.DomHelper()));
86 };
87
88
89 /**
90 * Cached default DOM helper.
91 * @type {!goog.dom.DomHelper|undefined}
92 * @private
93 */
94 goog.dom.defaultDomHelper_;
95
96
97 /**
98 * Gets the document object being used by the dom library.
99 * @return {!Document} Document object.
100 */
101 goog.dom.getDocument = function() {
102 return document;
103 };
104
105
106 /**
107 * Gets an element from the current document by element id.
108 *
109 * If an Element is passed in, it is returned.
110 *
111 * @param {string|Element} element Element ID or a DOM node.
112 * @return {Element} The element with the given ID, or the node passed in.
113 */
114 goog.dom.getElement = function(element) {
115 return goog.dom.getElementHelper_(document, element);
116 };
117
118
119 /**
120 * Gets an element by id from the given document (if present).
121 * If an element is given, it is returned.
122 * @param {!Document} doc
123 * @param {string|Element} element Element ID or a DOM node.
124 * @return {Element} The resulting element.
125 * @private
126 */
127 goog.dom.getElementHelper_ = function(doc, element) {
128 return goog.isString(element) ? doc.getElementById(element) : element;
129 };
130
131
132 /**
133 * Gets an element by id, asserting that the element is found.
134 *
135 * This is used when an element is expected to exist, and should fail with
136 * an assertion error if it does not (if assertions are enabled).
137 *
138 * @param {string} id Element ID.
139 * @return {!Element} The element with the given ID, if it exists.
140 */
141 goog.dom.getRequiredElement = function(id) {
142 return goog.dom.getRequiredElementHelper_(document, id);
143 };
144
145
146 /**
147 * Helper function for getRequiredElementHelper functions, both static and
148 * on DomHelper. Asserts the element with the given id exists.
149 * @param {!Document} doc
150 * @param {string} id
151 * @return {!Element} The element with the given ID, if it exists.
152 * @private
153 */
154 goog.dom.getRequiredElementHelper_ = function(doc, id) {
155 // To prevent users passing in Elements as is permitted in getElement().
156 goog.asserts.assertString(id);
157 var element = goog.dom.getElementHelper_(doc, id);
158 element =
159 goog.asserts.assertElement(element, 'No element found with id: ' + id);
160 return element;
161 };
162
163
164 /**
165 * Alias for getElement.
166 * @param {string|Element} element Element ID or a DOM node.
167 * @return {Element} The element with the given ID, or the node passed in.
168 * @deprecated Use {@link goog.dom.getElement} instead.
169 */
170 goog.dom.$ = goog.dom.getElement;
171
172
173 /**
174 * Gets elements by tag name.
175 * @param {!goog.dom.TagName<T>} tagName
176 * @param {(!Document|!Element)=} opt_parent Parent element or document where to
177 * look for elements. Defaults to document.
178 * @return {!NodeList<R>} List of elements. The members of the list are
179 * {!Element} if tagName is not a member of goog.dom.TagName or more
180 * specific types if it is (e.g. {!HTMLAnchorElement} for
181 * goog.dom.TagName.A).
182 * @template T
183 * @template R := cond(isUnknown(T), 'Element', T) =:
184 */
185 goog.dom.getElementsByTagName = function(tagName, opt_parent) {
186 var parent = opt_parent || document;
187 return parent.getElementsByTagName(String(tagName));
188 };
189
190
191 /**
192 * Looks up elements by both tag and class name, using browser native functions
193 * ({@code querySelectorAll}, {@code getElementsByTagName} or
194 * {@code getElementsByClassName}) where possible. This function
195 * is a useful, if limited, way of collecting a list of DOM elements
196 * with certain characteristics. {@code goog.dom.query} offers a
197 * more powerful and general solution which allows matching on CSS3
198 * selector expressions, but at increased cost in code size. If all you
199 * need is particular tags belonging to a single class, this function
200 * is fast and sleek.
201 *
202 * Note that tag names are case sensitive in the SVG namespace, and this
203 * function converts opt_tag to uppercase for comparisons. For queries in the
204 * SVG namespace you should use querySelector or querySelectorAll instead.
205 * https://bugzilla.mozilla.org/show_bug.cgi?id=963870
206 * https://bugs.webkit.org/show_bug.cgi?id=83438
207 *
208 * @see {goog.dom.query}
209 *
210 * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.
211 * @param {?string=} opt_class Optional class name.
212 * @param {(Document|Element)=} opt_el Optional element to look in.
213 * @return {!IArrayLike<R>} Array-like list of elements (only a length property
214 * and numerical indices are guaranteed to exist). The members of the array
215 * are {!Element} if opt_tag is not a member of goog.dom.TagName or more
216 * specific types if it is (e.g. {!HTMLAnchorElement} for
217 * goog.dom.TagName.A).
218 * @template T
219 * @template R := cond(isUnknown(T), 'Element', T) =:
220 */
221 goog.dom.getElementsByTagNameAndClass = function(opt_tag, opt_class, opt_el) {
222 return goog.dom.getElementsByTagNameAndClass_(
223 document, opt_tag, opt_class, opt_el);
224 };
225
226
227 /**
228 * Gets the first element matching the tag and the class.
229 *
230 * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.
231 * @param {?string=} opt_class Optional class name.
232 * @param {(Document|Element)=} opt_el Optional element to look in.
233 * @return {?R} Reference to a DOM node. The return type is {?Element} if
234 * tagName is a string or a more specific type if it is a member of
235 * goog.dom.TagName (e.g. {?HTMLAnchorElement} for goog.dom.TagName.A).
236 * @template T
237 * @template R := cond(isUnknown(T), 'Element', T) =:
238 */
239 goog.dom.getElementByTagNameAndClass = function(opt_tag, opt_class, opt_el) {
240 return goog.dom.getElementByTagNameAndClass_(
241 document, opt_tag, opt_class, opt_el);
242 };
243
244
245 /**
246 * Returns a static, array-like list of the elements with the provided
247 * className.
248 * @see {goog.dom.query}
249 * @param {string} className the name of the class to look for.
250 * @param {(Document|Element)=} opt_el Optional element to look in.
251 * @return {!IArrayLike<!Element>} The items found with the class name provided.
252 */
253 goog.dom.getElementsByClass = function(className, opt_el) {
254 var parent = opt_el || document;
255 if (goog.dom.canUseQuerySelector_(parent)) {
256 return parent.querySelectorAll('.' + className);
257 }
258 return goog.dom.getElementsByTagNameAndClass_(
259 document, '*', className, opt_el);
260 };
261
262
263 /**
264 * Returns the first element with the provided className.
265 * @see {goog.dom.query}
266 * @param {string} className the name of the class to look for.
267 * @param {Element|Document=} opt_el Optional element to look in.
268 * @return {Element} The first item with the class name provided.
269 */
270 goog.dom.getElementByClass = function(className, opt_el) {
271 var parent = opt_el || document;
272 var retVal = null;
273 if (parent.getElementsByClassName) {
274 retVal = parent.getElementsByClassName(className)[0];
275 } else {
276 retVal =
277 goog.dom.getElementByTagNameAndClass_(document, '*', className, opt_el);
278 }
279 return retVal || null;
280 };
281
282
283 /**
284 * Ensures an element with the given className exists, and then returns the
285 * first element with the provided className.
286 * @see {goog.dom.query}
287 * @param {string} className the name of the class to look for.
288 * @param {!Element|!Document=} opt_root Optional element or document to look
289 * in.
290 * @return {!Element} The first item with the class name provided.
291 * @throws {goog.asserts.AssertionError} Thrown if no element is found.
292 */
293 goog.dom.getRequiredElementByClass = function(className, opt_root) {
294 var retValue = goog.dom.getElementByClass(className, opt_root);
295 return goog.asserts.assert(
296 retValue, 'No element found with className: ' + className);
297 };
298
299
300 /**
301 * Prefer the standardized (http://www.w3.org/TR/selectors-api/), native and
302 * fast W3C Selectors API.
303 * @param {!(Element|Document)} parent The parent document object.
304 * @return {boolean} whether or not we can use parent.querySelector* APIs.
305 * @private
306 */
307 goog.dom.canUseQuerySelector_ = function(parent) {
308 return !!(parent.querySelectorAll && parent.querySelector);
309 };
310
311
312 /**
313 * Helper for {@code getElementsByTagNameAndClass}.
314 * @param {!Document} doc The document to get the elements in.
315 * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.
316 * @param {?string=} opt_class Optional class name.
317 * @param {(Document|Element)=} opt_el Optional element to look in.
318 * @return {!IArrayLike<R>} Array-like list of elements (only a length property
319 * and numerical indices are guaranteed to exist). The members of the array
320 * are {!Element} if opt_tag is not a member of goog.dom.TagName or more
321 * specific types if it is (e.g. {!HTMLAnchorElement} for
322 * goog.dom.TagName.A).
323 * @template T
324 * @template R := cond(isUnknown(T), 'Element', T) =:
325 * @private
326 */
327 goog.dom.getElementsByTagNameAndClass_ = function(
328 doc, opt_tag, opt_class, opt_el) {
329 var parent = opt_el || doc;
330 var tagName =
331 (opt_tag && opt_tag != '*') ? String(opt_tag).toUpperCase() : '';
332
333 if (goog.dom.canUseQuerySelector_(parent) && (tagName || opt_class)) {
334 var query = tagName + (opt_class ? '.' + opt_class : '');
335 return parent.querySelectorAll(query);
336 }
337
338 // Use the native getElementsByClassName if available, under the assumption
339 // that even when the tag name is specified, there will be fewer elements to
340 // filter through when going by class than by tag name
341 if (opt_class && parent.getElementsByClassName) {
342 var els = parent.getElementsByClassName(opt_class);
343
344 if (tagName) {
345 var arrayLike = {};
346 var len = 0;
347
348 // Filter for specific tags if requested.
349 for (var i = 0, el; el = els[i]; i++) {
350 if (tagName == el.nodeName) {
351 arrayLike[len++] = el;
352 }
353 }
354 arrayLike.length = len;
355
356 return /** @type {!IArrayLike<!Element>} */ (arrayLike);
357 } else {
358 return els;
359 }
360 }
361
362 var els = parent.getElementsByTagName(tagName || '*');
363
364 if (opt_class) {
365 var arrayLike = {};
366 var len = 0;
367 for (var i = 0, el; el = els[i]; i++) {
368 var className = el.className;
369 // Check if className has a split function since SVG className does not.
370 if (typeof className.split == 'function' &&
371 goog.array.contains(className.split(/\s+/), opt_class)) {
372 arrayLike[len++] = el;
373 }
374 }
375 arrayLike.length = len;
376 return /** @type {!IArrayLike<!Element>} */ (arrayLike);
377 } else {
378 return els;
379 }
380 };
381
382
383 /**
384 * Helper for goog.dom.getElementByTagNameAndClass.
385 *
386 * @param {!Document} doc The document to get the elements in.
387 * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.
388 * @param {?string=} opt_class Optional class name.
389 * @param {(Document|Element)=} opt_el Optional element to look in.
390 * @return {?R} Reference to a DOM node. The return type is {?Element} if
391 * tagName is a string or a more specific type if it is a member of
392 * goog.dom.TagName (e.g. {?HTMLAnchorElement} for goog.dom.TagName.A).
393 * @template T
394 * @template R := cond(isUnknown(T), 'Element', T) =:
395 * @private
396 */
397 goog.dom.getElementByTagNameAndClass_ = function(
398 doc, opt_tag, opt_class, opt_el) {
399 var parent = opt_el || doc;
400 var tag = (opt_tag && opt_tag != '*') ? String(opt_tag).toUpperCase() : '';
401 if (goog.dom.canUseQuerySelector_(parent) && (tag || opt_class)) {
402 return parent.querySelector(tag + (opt_class ? '.' + opt_class : ''));
403 }
404 var elements =
405 goog.dom.getElementsByTagNameAndClass_(doc, opt_tag, opt_class, opt_el);
406 return elements[0] || null;
407 };
408
409
410
411 /**
412 * Alias for {@code getElementsByTagNameAndClass}.
413 * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.
414 * @param {?string=} opt_class Optional class name.
415 * @param {Element=} opt_el Optional element to look in.
416 * @return {!IArrayLike<R>} Array-like list of elements (only a length property
417 * and numerical indices are guaranteed to exist). The members of the array
418 * are {!Element} if opt_tag is not a member of goog.dom.TagName or more
419 * specific types if it is (e.g. {!HTMLAnchorElement} for
420 * goog.dom.TagName.A).
421 * @template T
422 * @template R := cond(isUnknown(T), 'Element', T) =:
423 * @deprecated Use {@link goog.dom.getElementsByTagNameAndClass} instead.
424 */
425 goog.dom.$$ = goog.dom.getElementsByTagNameAndClass;
426
427
428 /**
429 * Sets multiple properties, and sometimes attributes, on an element. Note that
430 * properties are simply object properties on the element instance, while
431 * attributes are visible in the DOM. Many properties map to attributes with the
432 * same names, some with different names, and there are also unmappable cases.
433 *
434 * This method sets properties by default (which means that custom attributes
435 * are not supported). These are the exeptions (some of which is legacy):
436 * - "style": Even though this is an attribute name, it is translated to a
437 * property, "style.cssText". Note that this property sanitizes and formats
438 * its value, unlike the attribute.
439 * - "class": This is an attribute name, it is translated to the "className"
440 * property.
441 * - "for": This is an attribute name, it is translated to the "htmlFor"
442 * property.
443 * - Entries in {@see goog.dom.DIRECT_ATTRIBUTE_MAP_} are set as attributes,
444 * this is probably due to browser quirks.
445 * - "aria-*", "data-*": Always set as attributes, they have no property
446 * counterparts.
447 *
448 * @param {Element} element DOM node to set properties on.
449 * @param {Object} properties Hash of property:value pairs.
450 * Property values can be strings or goog.string.TypedString values (such as
451 * goog.html.SafeUrl).
452 */
453 goog.dom.setProperties = function(element, properties) {
454 goog.object.forEach(properties, function(val, key) {
455 if (val && val.implementsGoogStringTypedString) {
456 val = val.getTypedStringValue();
457 }
458 if (key == 'style') {
459 element.style.cssText = val;
460 } else if (key == 'class') {
461 element.className = val;
462 } else if (key == 'for') {
463 element.htmlFor = val;
464 } else if (goog.dom.DIRECT_ATTRIBUTE_MAP_.hasOwnProperty(key)) {
465 element.setAttribute(goog.dom.DIRECT_ATTRIBUTE_MAP_[key], val);
466 } else if (
467 goog.string.startsWith(key, 'aria-') ||
468 goog.string.startsWith(key, 'data-')) {
469 element.setAttribute(key, val);
470 } else {
471 element[key] = val;
472 }
473 });
474 };
475
476
477 /**
478 * Map of attributes that should be set using
479 * element.setAttribute(key, val) instead of element[key] = val. Used
480 * by goog.dom.setProperties.
481 *
482 * @private {!Object<string, string>}
483 * @const
484 */
485 goog.dom.DIRECT_ATTRIBUTE_MAP_ = {
486 'cellpadding': 'cellPadding',
487 'cellspacing': 'cellSpacing',
488 'colspan': 'colSpan',
489 'frameborder': 'frameBorder',
490 'height': 'height',
491 'maxlength': 'maxLength',
492 'nonce': 'nonce',
493 'role': 'role',
494 'rowspan': 'rowSpan',
495 'type': 'type',
496 'usemap': 'useMap',
497 'valign': 'vAlign',
498 'width': 'width'
499 };
500
501
502 /**
503 * Gets the dimensions of the viewport.
504 *
505 * Gecko Standards mode:
506 * docEl.clientWidth Width of viewport excluding scrollbar.
507 * win.innerWidth Width of viewport including scrollbar.
508 * body.clientWidth Width of body element.
509 *
510 * docEl.clientHeight Height of viewport excluding scrollbar.
511 * win.innerHeight Height of viewport including scrollbar.
512 * body.clientHeight Height of document.
513 *
514 * Gecko Backwards compatible mode:
515 * docEl.clientWidth Width of viewport excluding scrollbar.
516 * win.innerWidth Width of viewport including scrollbar.
517 * body.clientWidth Width of viewport excluding scrollbar.
518 *
519 * docEl.clientHeight Height of document.
520 * win.innerHeight Height of viewport including scrollbar.
521 * body.clientHeight Height of viewport excluding scrollbar.
522 *
523 * IE6/7 Standards mode:
524 * docEl.clientWidth Width of viewport excluding scrollbar.
525 * win.innerWidth Undefined.
526 * body.clientWidth Width of body element.
527 *
528 * docEl.clientHeight Height of viewport excluding scrollbar.
529 * win.innerHeight Undefined.
530 * body.clientHeight Height of document element.
531 *
532 * IE5 + IE6/7 Backwards compatible mode:
533 * docEl.clientWidth 0.
534 * win.innerWidth Undefined.
535 * body.clientWidth Width of viewport excluding scrollbar.
536 *
537 * docEl.clientHeight 0.
538 * win.innerHeight Undefined.
539 * body.clientHeight Height of viewport excluding scrollbar.
540 *
541 * Opera 9 Standards and backwards compatible mode:
542 * docEl.clientWidth Width of viewport excluding scrollbar.
543 * win.innerWidth Width of viewport including scrollbar.
544 * body.clientWidth Width of viewport excluding scrollbar.
545 *
546 * docEl.clientHeight Height of document.
547 * win.innerHeight Height of viewport including scrollbar.
548 * body.clientHeight Height of viewport excluding scrollbar.
549 *
550 * WebKit:
551 * Safari 2
552 * docEl.clientHeight Same as scrollHeight.
553 * docEl.clientWidth Same as innerWidth.
554 * win.innerWidth Width of viewport excluding scrollbar.
555 * win.innerHeight Height of the viewport including scrollbar.
556 * frame.innerHeight Height of the viewport exluding scrollbar.
557 *
558 * Safari 3 (tested in 522)
559 *
560 * docEl.clientWidth Width of viewport excluding scrollbar.
561 * docEl.clientHeight Height of viewport excluding scrollbar in strict mode.
562 * body.clientHeight Height of viewport excluding scrollbar in quirks mode.
563 *
564 * @param {Window=} opt_window Optional window element to test.
565 * @return {!goog.math.Size} Object with values 'width' and 'height'.
566 */
567 goog.dom.getViewportSize = function(opt_window) {
568 // TODO(arv): This should not take an argument
569 return goog.dom.getViewportSize_(opt_window || window);
570 };
571
572
573 /**
574 * Helper for {@code getViewportSize}.
575 * @param {Window} win The window to get the view port size for.
576 * @return {!goog.math.Size} Object with values 'width' and 'height'.
577 * @private
578 */
579 goog.dom.getViewportSize_ = function(win) {
580 var doc = win.document;
581 var el = goog.dom.isCss1CompatMode_(doc) ? doc.documentElement : doc.body;
582 return new goog.math.Size(el.clientWidth, el.clientHeight);
583 };
584
585
586 /**
587 * Calculates the height of the document.
588 *
589 * @return {number} The height of the current document.
590 */
591 goog.dom.getDocumentHeight = function() {
592 return goog.dom.getDocumentHeight_(window);
593 };
594
595 /**
596 * Calculates the height of the document of the given window.
597 *
598 * @param {!Window} win The window whose document height to retrieve.
599 * @return {number} The height of the document of the given window.
600 */
601 goog.dom.getDocumentHeightForWindow = function(win) {
602 return goog.dom.getDocumentHeight_(win);
603 };
604
605 /**
606 * Calculates the height of the document of the given window.
607 *
608 * Function code copied from the opensocial gadget api:
609 * gadgets.window.adjustHeight(opt_height)
610 *
611 * @private
612 * @param {!Window} win The window whose document height to retrieve.
613 * @return {number} The height of the document of the given window.
614 */
615 goog.dom.getDocumentHeight_ = function(win) {
616 // NOTE(eae): This method will return the window size rather than the document
617 // size in webkit quirks mode.
618 var doc = win.document;
619 var height = 0;
620
621 if (doc) {
622 // Calculating inner content height is hard and different between
623 // browsers rendering in Strict vs. Quirks mode. We use a combination of
624 // three properties within document.body and document.documentElement:
625 // - scrollHeight
626 // - offsetHeight
627 // - clientHeight
628 // These values differ significantly between browsers and rendering modes.
629 // But there are patterns. It just takes a lot of time and persistence
630 // to figure out.
631
632 var body = doc.body;
633 var docEl = /** @type {!HTMLElement} */ (doc.documentElement);
634 if (!(docEl && body)) {
635 return 0;
636 }
637
638 // Get the height of the viewport
639 var vh = goog.dom.getViewportSize_(win).height;
640 if (goog.dom.isCss1CompatMode_(doc) && docEl.scrollHeight) {
641 // In Strict mode:
642 // The inner content height is contained in either:
643 // document.documentElement.scrollHeight
644 // document.documentElement.offsetHeight
645 // Based on studying the values output by different browsers,
646 // use the value that's NOT equal to the viewport height found above.
647 height =
648 docEl.scrollHeight != vh ? docEl.scrollHeight : docEl.offsetHeight;
649 } else {
650 // In Quirks mode:
651 // documentElement.clientHeight is equal to documentElement.offsetHeight
652 // except in IE. In most browsers, document.documentElement can be used
653 // to calculate the inner content height.
654 // However, in other browsers (e.g. IE), document.body must be used
655 // instead. How do we know which one to use?
656 // If document.documentElement.clientHeight does NOT equal
657 // document.documentElement.offsetHeight, then use document.body.
658 var sh = docEl.scrollHeight;
659 var oh = docEl.offsetHeight;
660 if (docEl.clientHeight != oh) {
661 sh = body.scrollHeight;
662 oh = body.offsetHeight;
663 }
664
665 // Detect whether the inner content height is bigger or smaller
666 // than the bounding box (viewport). If bigger, take the larger
667 // value. If smaller, take the smaller value.
668 if (sh > vh) {
669 // Content is larger
670 height = sh > oh ? sh : oh;
671 } else {
672 // Content is smaller
673 height = sh < oh ? sh : oh;
674 }
675 }
676 }
677
678 return height;
679 };
680
681
682 /**
683 * Gets the page scroll distance as a coordinate object.
684 *
685 * @param {Window=} opt_window Optional window element to test.
686 * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.
687 * @deprecated Use {@link goog.dom.getDocumentScroll} instead.
688 */
689 goog.dom.getPageScroll = function(opt_window) {
690 var win = opt_window || goog.global || window;
691 return goog.dom.getDomHelper(win.document).getDocumentScroll();
692 };
693
694
695 /**
696 * Gets the document scroll distance as a coordinate object.
697 *
698 * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.
699 */
700 goog.dom.getDocumentScroll = function() {
701 return goog.dom.getDocumentScroll_(document);
702 };
703
704
705 /**
706 * Helper for {@code getDocumentScroll}.
707 *
708 * @param {!Document} doc The document to get the scroll for.
709 * @return {!goog.math.Coordinate} Object with values 'x' and 'y'.
710 * @private
711 */
712 goog.dom.getDocumentScroll_ = function(doc) {
713 var el = goog.dom.getDocumentScrollElement_(doc);
714 var win = goog.dom.getWindow_(doc);
715 if (goog.userAgent.IE && goog.userAgent.isVersionOrHigher('10') &&
716 win.pageYOffset != el.scrollTop) {
717 // The keyboard on IE10 touch devices shifts the page using the pageYOffset
718 // without modifying scrollTop. For this case, we want the body scroll
719 // offsets.
720 return new goog.math.Coordinate(el.scrollLeft, el.scrollTop);
721 }
722 return new goog.math.Coordinate(
723 win.pageXOffset || el.scrollLeft, win.pageYOffset || el.scrollTop);
724 };
725
726
727 /**
728 * Gets the document scroll element.
729 * @return {!Element} Scrolling element.
730 */
731 goog.dom.getDocumentScrollElement = function() {
732 return goog.dom.getDocumentScrollElement_(document);
733 };
734
735
736 /**
737 * Helper for {@code getDocumentScrollElement}.
738 * @param {!Document} doc The document to get the scroll element for.
739 * @return {!Element} Scrolling element.
740 * @private
741 */
742 goog.dom.getDocumentScrollElement_ = function(doc) {
743 // Old WebKit needs body.scrollLeft in both quirks mode and strict mode. We
744 // also default to the documentElement if the document does not have a body
745 // (e.g. a SVG document).
746 // Uses http://dev.w3.org/csswg/cssom-view/#dom-document-scrollingelement to
747 // avoid trying to guess about browser behavior from the UA string.
748 if (doc.scrollingElement) {
749 return doc.scrollingElement;
750 }
751 if (!goog.userAgent.WEBKIT && goog.dom.isCss1CompatMode_(doc)) {
752 return doc.documentElement;
753 }
754 return doc.body || doc.documentElement;
755 };
756
757
758 /**
759 * Gets the window object associated with the given document.
760 *
761 * @param {Document=} opt_doc Document object to get window for.
762 * @return {!Window} The window associated with the given document.
763 */
764 goog.dom.getWindow = function(opt_doc) {
765 // TODO(arv): This should not take an argument.
766 return opt_doc ? goog.dom.getWindow_(opt_doc) : window;
767 };
768
769
770 /**
771 * Helper for {@code getWindow}.
772 *
773 * @param {!Document} doc Document object to get window for.
774 * @return {!Window} The window associated with the given document.
775 * @private
776 */
777 goog.dom.getWindow_ = function(doc) {
778 return /** @type {!Window} */ (doc.parentWindow || doc.defaultView);
779 };
780
781
782 /**
783 * Returns a dom node with a set of attributes. This function accepts varargs
784 * for subsequent nodes to be added. Subsequent nodes will be added to the
785 * first node as childNodes.
786 *
787 * So:
788 * <code>createDom(goog.dom.TagName.DIV, null, createDom(goog.dom.TagName.P),
789 * createDom(goog.dom.TagName.P));</code> would return a div with two child
790 * paragraphs
791 *
792 * For passing properties, please see {@link goog.dom.setProperties} for more
793 * information.
794 *
795 * @param {string|!goog.dom.TagName<T>} tagName Tag to create.
796 * @param {?Object|?Array<string>|string=} opt_attributes If object, then a map
797 * of name-value pairs for attributes. If a string, then this is the
798 * className of the new element. If an array, the elements will be joined
799 * together as the className of the new element.
800 * @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or
801 * strings for text nodes. If one of the var_args is an array or NodeList,
802 * its elements will be added as childNodes instead.
803 * @return {R} Reference to a DOM node. The return type is {!Element} if tagName
804 * is a string or a more specific type if it is a member of
805 * goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).
806 * @template T
807 * @template R := cond(isUnknown(T), 'Element', T) =:
808 */
809 goog.dom.createDom = function(tagName, opt_attributes, var_args) {
810 return goog.dom.createDom_(document, arguments);
811 };
812
813
814 /**
815 * Helper for {@code createDom}.
816 * @param {!Document} doc The document to create the DOM in.
817 * @param {!Arguments} args Argument object passed from the callers. See
818 * {@code goog.dom.createDom} for details.
819 * @return {!Element} Reference to a DOM node.
820 * @private
821 */
822 goog.dom.createDom_ = function(doc, args) {
823 var tagName = String(args[0]);
824 var attributes = args[1];
825
826 // Internet Explorer is dumb:
827 // name: https://msdn.microsoft.com/en-us/library/ms534184(v=vs.85).aspx
828 // type: https://msdn.microsoft.com/en-us/library/ms534700(v=vs.85).aspx
829 // Also does not allow setting of 'type' attribute on 'input' or 'button'.
830 if (!goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES && attributes &&
831 (attributes.name || attributes.type)) {
832 var tagNameArr = ['<', tagName];
833 if (attributes.name) {
834 tagNameArr.push(' name="', goog.string.htmlEscape(attributes.name), '"');
835 }
836 if (attributes.type) {
837 tagNameArr.push(' type="', goog.string.htmlEscape(attributes.type), '"');
838
839 // Clone attributes map to remove 'type' without mutating the input.
840 var clone = {};
841 goog.object.extend(clone, attributes);
842
843 // JSCompiler can't see how goog.object.extend added this property,
844 // because it was essentially added by reflection.
845 // So it needs to be quoted.
846 delete clone['type'];
847
848 attributes = clone;
849 }
850 tagNameArr.push('>');
851 tagName = tagNameArr.join('');
852 }
853
854 var element = doc.createElement(tagName);
855
856 if (attributes) {
857 if (goog.isString(attributes)) {
858 element.className = attributes;
859 } else if (goog.isArray(attributes)) {
860 element.className = attributes.join(' ');
861 } else {
862 goog.dom.setProperties(element, attributes);
863 }
864 }
865
866 if (args.length > 2) {
867 goog.dom.append_(doc, element, args, 2);
868 }
869
870 return element;
871 };
872
873
874 /**
875 * Appends a node with text or other nodes.
876 * @param {!Document} doc The document to create new nodes in.
877 * @param {!Node} parent The node to append nodes to.
878 * @param {!Arguments} args The values to add. See {@code goog.dom.append}.
879 * @param {number} startIndex The index of the array to start from.
880 * @private
881 */
882 goog.dom.append_ = function(doc, parent, args, startIndex) {
883 function childHandler(child) {
884 // TODO(user): More coercion, ala MochiKit?
885 if (child) {
886 parent.appendChild(
887 goog.isString(child) ? doc.createTextNode(child) : child);
888 }
889 }
890
891 for (var i = startIndex; i < args.length; i++) {
892 var arg = args[i];
893 // TODO(attila): Fix isArrayLike to return false for a text node.
894 if (goog.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) {
895 // If the argument is a node list, not a real array, use a clone,
896 // because forEach can't be used to mutate a NodeList.
897 goog.array.forEach(
898 goog.dom.isNodeList(arg) ? goog.array.toArray(arg) : arg,
899 childHandler);
900 } else {
901 childHandler(arg);
902 }
903 }
904 };
905
906
907 /**
908 * Alias for {@code createDom}.
909 * @param {string|!goog.dom.TagName<T>} tagName Tag to create.
910 * @param {?Object|?Array<string>|string=} opt_attributes If object, then a map
911 * of name-value pairs for attributes. If a string, then this is the
912 * className of the new element. If an array, the elements will be joined
913 * together as the className of the new element.
914 * @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or
915 * strings for text nodes. If one of the var_args is an array, its
916 * children will be added as childNodes instead.
917 * @return {R} Reference to a DOM node. The return type is {!Element} if tagName
918 * is a string or a more specific type if it is a member of
919 * goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).
920 * @template T
921 * @template R := cond(isUnknown(T), 'Element', T) =:
922 * @deprecated Use {@link goog.dom.createDom} instead.
923 */
924 goog.dom.$dom = goog.dom.createDom;
925
926
927 /**
928 * Creates a new element.
929 * @param {string|!goog.dom.TagName<T>} name Tag to create.
930 * @return {R} The new element. The return type is {!Element} if name is
931 * a string or a more specific type if it is a member of goog.dom.TagName
932 * (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).
933 * @template T
934 * @template R := cond(isUnknown(T), 'Element', T) =:
935 */
936 goog.dom.createElement = function(name) {
937 return goog.dom.createElement_(document, name);
938 };
939
940
941 /**
942 * Creates a new element.
943 * @param {!Document} doc The document to create the element in.
944 * @param {string|!goog.dom.TagName<T>} name Tag to create.
945 * @return {R} The new element. The return type is {!Element} if name is
946 * a string or a more specific type if it is a member of goog.dom.TagName
947 * (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).
948 * @template T
949 * @template R := cond(isUnknown(T), 'Element', T) =:
950 * @private
951 */
952 goog.dom.createElement_ = function(doc, name) {
953 return doc.createElement(String(name));
954 };
955
956
957 /**
958 * Creates a new text node.
959 * @param {number|string} content Content.
960 * @return {!Text} The new text node.
961 */
962 goog.dom.createTextNode = function(content) {
963 return document.createTextNode(String(content));
964 };
965
966
967 /**
968 * Create a table.
969 * @param {number} rows The number of rows in the table. Must be >= 1.
970 * @param {number} columns The number of columns in the table. Must be >= 1.
971 * @param {boolean=} opt_fillWithNbsp If true, fills table entries with
972 * {@code goog.string.Unicode.NBSP} characters.
973 * @return {!Element} The created table.
974 */
975 goog.dom.createTable = function(rows, columns, opt_fillWithNbsp) {
976 // TODO(mlourenco): Return HTMLTableElement, also in prototype function.
977 // Callers need to be updated to e.g. not assign numbers to table.cellSpacing.
978 return goog.dom.createTable_(document, rows, columns, !!opt_fillWithNbsp);
979 };
980
981
982 /**
983 * Create a table.
984 * @param {!Document} doc Document object to use to create the table.
985 * @param {number} rows The number of rows in the table. Must be >= 1.
986 * @param {number} columns The number of columns in the table. Must be >= 1.
987 * @param {boolean} fillWithNbsp If true, fills table entries with
988 * {@code goog.string.Unicode.NBSP} characters.
989 * @return {!HTMLTableElement} The created table.
990 * @private
991 */
992 goog.dom.createTable_ = function(doc, rows, columns, fillWithNbsp) {
993 var table = goog.dom.createElement_(doc, goog.dom.TagName.TABLE);
994 var tbody =
995 table.appendChild(goog.dom.createElement_(doc, goog.dom.TagName.TBODY));
996 for (var i = 0; i < rows; i++) {
997 var tr = goog.dom.createElement_(doc, goog.dom.TagName.TR);
998 for (var j = 0; j < columns; j++) {
999 var td = goog.dom.createElement_(doc, goog.dom.TagName.TD);
1000 // IE <= 9 will create a text node if we set text content to the empty
1001 // string, so we avoid doing it unless necessary. This ensures that the
1002 // same DOM tree is returned on all browsers.
1003 if (fillWithNbsp) {
1004 goog.dom.setTextContent(td, goog.string.Unicode.NBSP);
1005 }
1006 tr.appendChild(td);
1007 }
1008 tbody.appendChild(tr);
1009 }
1010 return table;
1011 };
1012
1013
1014
1015 /**
1016 * Creates a new Node from constant strings of HTML markup.
1017 * @param {...!goog.string.Const} var_args The HTML strings to concatenate then
1018 * convert into a node.
1019 * @return {!Node}
1020 */
1021 goog.dom.constHtmlToNode = function(var_args) {
1022 var stringArray = goog.array.map(arguments, goog.string.Const.unwrap);
1023 var safeHtml =
1024 goog.html.uncheckedconversions
1025 .safeHtmlFromStringKnownToSatisfyTypeContract(
1026 goog.string.Const.from(
1027 'Constant HTML string, that gets turned into a ' +
1028 'Node later, so it will be automatically balanced.'),
1029 stringArray.join(''));
1030 return goog.dom.safeHtmlToNode(safeHtml);
1031 };
1032
1033
1034 /**
1035 * Converts HTML markup into a node. This is a safe version of
1036 * {@code goog.dom.htmlToDocumentFragment} which is now deleted.
1037 * @param {!goog.html.SafeHtml} html The HTML markup to convert.
1038 * @return {!Node} The resulting node.
1039 */
1040 goog.dom.safeHtmlToNode = function(html) {
1041 return goog.dom.safeHtmlToNode_(document, html);
1042 };
1043
1044
1045 /**
1046 * Helper for {@code safeHtmlToNode}.
1047 * @param {!Document} doc The document.
1048 * @param {!goog.html.SafeHtml} html The HTML markup to convert.
1049 * @return {!Node} The resulting node.
1050 * @private
1051 */
1052 goog.dom.safeHtmlToNode_ = function(doc, html) {
1053 var tempDiv = goog.dom.createElement_(doc, goog.dom.TagName.DIV);
1054 if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) {
1055 goog.dom.safe.setInnerHtml(
1056 tempDiv, goog.html.SafeHtml.concat(goog.html.SafeHtml.BR, html));
1057 tempDiv.removeChild(tempDiv.firstChild);
1058 } else {
1059 goog.dom.safe.setInnerHtml(tempDiv, html);
1060 }
1061 return goog.dom.childrenToNode_(doc, tempDiv);
1062 };
1063
1064
1065 /**
1066 * Helper for {@code safeHtmlToNode_}.
1067 * @param {!Document} doc The document.
1068 * @param {!Node} tempDiv The input node.
1069 * @return {!Node} The resulting node.
1070 * @private
1071 */
1072 goog.dom.childrenToNode_ = function(doc, tempDiv) {
1073 if (tempDiv.childNodes.length == 1) {
1074 return tempDiv.removeChild(tempDiv.firstChild);
1075 } else {
1076 var fragment = doc.createDocumentFragment();
1077 while (tempDiv.firstChild) {
1078 fragment.appendChild(tempDiv.firstChild);
1079 }
1080 return fragment;
1081 }
1082 };
1083
1084
1085 /**
1086 * Returns true if the browser is in "CSS1-compatible" (standards-compliant)
1087 * mode, false otherwise.
1088 * @return {boolean} True if in CSS1-compatible mode.
1089 */
1090 goog.dom.isCss1CompatMode = function() {
1091 return goog.dom.isCss1CompatMode_(document);
1092 };
1093
1094
1095 /**
1096 * Returns true if the browser is in "CSS1-compatible" (standards-compliant)
1097 * mode, false otherwise.
1098 * @param {!Document} doc The document to check.
1099 * @return {boolean} True if in CSS1-compatible mode.
1100 * @private
1101 */
1102 goog.dom.isCss1CompatMode_ = function(doc) {
1103 if (goog.dom.COMPAT_MODE_KNOWN_) {
1104 return goog.dom.ASSUME_STANDARDS_MODE;
1105 }
1106
1107 return doc.compatMode == 'CSS1Compat';
1108 };
1109
1110
1111 /**
1112 * Determines if the given node can contain children, intended to be used for
1113 * HTML generation.
1114 *
1115 * IE natively supports node.canHaveChildren but has inconsistent behavior.
1116 * Prior to IE8 the base tag allows children and in IE9 all nodes return true
1117 * for canHaveChildren.
1118 *
1119 * In practice all non-IE browsers allow you to add children to any node, but
1120 * the behavior is inconsistent:
1121 *
1122 * <pre>
1123 * var a = goog.dom.createElement(goog.dom.TagName.BR);
1124 * a.appendChild(document.createTextNode('foo'));
1125 * a.appendChild(document.createTextNode('bar'));
1126 * console.log(a.childNodes.length); // 2
1127 * console.log(a.innerHTML); // Chrome: "", IE9: "foobar", FF3.5: "foobar"
1128 * </pre>
1129 *
1130 * For more information, see:
1131 * http://dev.w3.org/html5/markup/syntax.html#syntax-elements
1132 *
1133 * TODO(user): Rename shouldAllowChildren() ?
1134 *
1135 * @param {Node} node The node to check.
1136 * @return {boolean} Whether the node can contain children.
1137 */
1138 goog.dom.canHaveChildren = function(node) {
1139 if (node.nodeType != goog.dom.NodeType.ELEMENT) {
1140 return false;
1141 }
1142 switch (/** @type {!Element} */ (node).tagName) {
1143 case String(goog.dom.TagName.APPLET):
1144 case String(goog.dom.TagName.AREA):
1145 case String(goog.dom.TagName.BASE):
1146 case String(goog.dom.TagName.BR):
1147 case String(goog.dom.TagName.COL):
1148 case String(goog.dom.TagName.COMMAND):
1149 case String(goog.dom.TagName.EMBED):
1150 case String(goog.dom.TagName.FRAME):
1151 case String(goog.dom.TagName.HR):
1152 case String(goog.dom.TagName.IMG):
1153 case String(goog.dom.TagName.INPUT):
1154 case String(goog.dom.TagName.IFRAME):
1155 case String(goog.dom.TagName.ISINDEX):
1156 case String(goog.dom.TagName.KEYGEN):
1157 case String(goog.dom.TagName.LINK):
1158 case String(goog.dom.TagName.NOFRAMES):
1159 case String(goog.dom.TagName.NOSCRIPT):
1160 case String(goog.dom.TagName.META):
1161 case String(goog.dom.TagName.OBJECT):
1162 case String(goog.dom.TagName.PARAM):
1163 case String(goog.dom.TagName.SCRIPT):
1164 case String(goog.dom.TagName.SOURCE):
1165 case String(goog.dom.TagName.STYLE):
1166 case String(goog.dom.TagName.TRACK):
1167 case String(goog.dom.TagName.WBR):
1168 return false;
1169 }
1170 return true;
1171 };
1172
1173
1174 /**
1175 * Appends a child to a node.
1176 * @param {Node} parent Parent.
1177 * @param {Node} child Child.
1178 */
1179 goog.dom.appendChild = function(parent, child) {
1180 parent.appendChild(child);
1181 };
1182
1183
1184 /**
1185 * Appends a node with text or other nodes.
1186 * @param {!Node} parent The node to append nodes to.
1187 * @param {...goog.dom.Appendable} var_args The things to append to the node.
1188 * If this is a Node it is appended as is.
1189 * If this is a string then a text node is appended.
1190 * If this is an array like object then fields 0 to length - 1 are appended.
1191 */
1192 goog.dom.append = function(parent, var_args) {
1193 goog.dom.append_(goog.dom.getOwnerDocument(parent), parent, arguments, 1);
1194 };
1195
1196
1197 /**
1198 * Removes all the child nodes on a DOM node.
1199 * @param {Node} node Node to remove children from.
1200 */
1201 goog.dom.removeChildren = function(node) {
1202 // Note: Iterations over live collections can be slow, this is the fastest
1203 // we could find. The double parenthesis are used to prevent JsCompiler and
1204 // strict warnings.
1205 var child;
1206 while ((child = node.firstChild)) {
1207 node.removeChild(child);
1208 }
1209 };
1210
1211
1212 /**
1213 * Inserts a new node before an existing reference node (i.e. as the previous
1214 * sibling). If the reference node has no parent, then does nothing.
1215 * @param {Node} newNode Node to insert.
1216 * @param {Node} refNode Reference node to insert before.
1217 */
1218 goog.dom.insertSiblingBefore = function(newNode, refNode) {
1219 if (refNode.parentNode) {
1220 refNode.parentNode.insertBefore(newNode, refNode);
1221 }
1222 };
1223
1224
1225 /**
1226 * Inserts a new node after an existing reference node (i.e. as the next
1227 * sibling). If the reference node has no parent, then does nothing.
1228 * @param {Node} newNode Node to insert.
1229 * @param {Node} refNode Reference node to insert after.
1230 */
1231 goog.dom.insertSiblingAfter = function(newNode, refNode) {
1232 if (refNode.parentNode) {
1233 refNode.parentNode.insertBefore(newNode, refNode.nextSibling);
1234 }
1235 };
1236
1237
1238 /**
1239 * Insert a child at a given index. If index is larger than the number of child
1240 * nodes that the parent currently has, the node is inserted as the last child
1241 * node.
1242 * @param {Element} parent The element into which to insert the child.
1243 * @param {Node} child The element to insert.
1244 * @param {number} index The index at which to insert the new child node. Must
1245 * not be negative.
1246 */
1247 goog.dom.insertChildAt = function(parent, child, index) {
1248 // Note that if the second argument is null, insertBefore
1249 // will append the child at the end of the list of children.
1250 parent.insertBefore(child, parent.childNodes[index] || null);
1251 };
1252
1253
1254 /**
1255 * Removes a node from its parent.
1256 * @param {Node} node The node to remove.
1257 * @return {Node} The node removed if removed; else, null.
1258 */
1259 goog.dom.removeNode = function(node) {
1260 return node && node.parentNode ? node.parentNode.removeChild(node) : null;
1261 };
1262
1263
1264 /**
1265 * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no
1266 * parent.
1267 * @param {Node} newNode Node to insert.
1268 * @param {Node} oldNode Node to replace.
1269 */
1270 goog.dom.replaceNode = function(newNode, oldNode) {
1271 var parent = oldNode.parentNode;
1272 if (parent) {
1273 parent.replaceChild(newNode, oldNode);
1274 }
1275 };
1276
1277
1278 /**
1279 * Flattens an element. That is, removes it and replace it with its children.
1280 * Does nothing if the element is not in the document.
1281 * @param {Element} element The element to flatten.
1282 * @return {Element|undefined} The original element, detached from the document
1283 * tree, sans children; or undefined, if the element was not in the document
1284 * to begin with.
1285 */
1286 goog.dom.flattenElement = function(element) {
1287 var child, parent = element.parentNode;
1288 if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) {
1289 // Use IE DOM method (supported by Opera too) if available
1290 if (element.removeNode) {
1291 return /** @type {Element} */ (element.removeNode(false));
1292 } else {
1293 // Move all children of the original node up one level.
1294 while ((child = element.firstChild)) {
1295 parent.insertBefore(child, element);
1296 }
1297
1298 // Detach the original element.
1299 return /** @type {Element} */ (goog.dom.removeNode(element));
1300 }
1301 }
1302 };
1303
1304
1305 /**
1306 * Returns an array containing just the element children of the given element.
1307 * @param {Element} element The element whose element children we want.
1308 * @return {!(Array<!Element>|NodeList<!Element>)} An array or array-like list
1309 * of just the element children of the given element.
1310 */
1311 goog.dom.getChildren = function(element) {
1312 // We check if the children attribute is supported for child elements
1313 // since IE8 misuses the attribute by also including comments.
1314 if (goog.dom.BrowserFeature.CAN_USE_CHILDREN_ATTRIBUTE &&
1315 element.children != undefined) {
1316 return element.children;
1317 }
1318 // Fall back to manually filtering the element's child nodes.
1319 return goog.array.filter(element.childNodes, function(node) {
1320 return node.nodeType == goog.dom.NodeType.ELEMENT;
1321 });
1322 };
1323
1324
1325 /**
1326 * Returns the first child node that is an element.
1327 * @param {Node} node The node to get the first child element of.
1328 * @return {Element} The first child node of {@code node} that is an element.
1329 */
1330 goog.dom.getFirstElementChild = function(node) {
1331 if (goog.isDef(node.firstElementChild)) {
1332 return /** @type {!Element} */ (node).firstElementChild;
1333 }
1334 return goog.dom.getNextElementNode_(node.firstChild, true);
1335 };
1336
1337
1338 /**
1339 * Returns the last child node that is an element.
1340 * @param {Node} node The node to get the last child element of.
1341 * @return {Element} The last child node of {@code node} that is an element.
1342 */
1343 goog.dom.getLastElementChild = function(node) {
1344 if (goog.isDef(node.lastElementChild)) {
1345 return /** @type {!Element} */ (node).lastElementChild;
1346 }
1347 return goog.dom.getNextElementNode_(node.lastChild, false);
1348 };
1349
1350
1351 /**
1352 * Returns the first next sibling that is an element.
1353 * @param {Node} node The node to get the next sibling element of.
1354 * @return {Element} The next sibling of {@code node} that is an element.
1355 */
1356 goog.dom.getNextElementSibling = function(node) {
1357 if (goog.isDef(node.nextElementSibling)) {
1358 return /** @type {!Element} */ (node).nextElementSibling;
1359 }
1360 return goog.dom.getNextElementNode_(node.nextSibling, true);
1361 };
1362
1363
1364 /**
1365 * Returns the first previous sibling that is an element.
1366 * @param {Node} node The node to get the previous sibling element of.
1367 * @return {Element} The first previous sibling of {@code node} that is
1368 * an element.
1369 */
1370 goog.dom.getPreviousElementSibling = function(node) {
1371 if (goog.isDef(node.previousElementSibling)) {
1372 return /** @type {!Element} */ (node).previousElementSibling;
1373 }
1374 return goog.dom.getNextElementNode_(node.previousSibling, false);
1375 };
1376
1377
1378 /**
1379 * Returns the first node that is an element in the specified direction,
1380 * starting with {@code node}.
1381 * @param {Node} node The node to get the next element from.
1382 * @param {boolean} forward Whether to look forwards or backwards.
1383 * @return {Element} The first element.
1384 * @private
1385 */
1386 goog.dom.getNextElementNode_ = function(node, forward) {
1387 while (node && node.nodeType != goog.dom.NodeType.ELEMENT) {
1388 node = forward ? node.nextSibling : node.previousSibling;
1389 }
1390
1391 return /** @type {Element} */ (node);
1392 };
1393
1394
1395 /**
1396 * Returns the next node in source order from the given node.
1397 * @param {Node} node The node.
1398 * @return {Node} The next node in the DOM tree, or null if this was the last
1399 * node.
1400 */
1401 goog.dom.getNextNode = function(node) {
1402 if (!node) {
1403 return null;
1404 }
1405
1406 if (node.firstChild) {
1407 return node.firstChild;
1408 }
1409
1410 while (node && !node.nextSibling) {
1411 node = node.parentNode;
1412 }
1413
1414 return node ? node.nextSibling : null;
1415 };
1416
1417
1418 /**
1419 * Returns the previous node in source order from the given node.
1420 * @param {Node} node The node.
1421 * @return {Node} The previous node in the DOM tree, or null if this was the
1422 * first node.
1423 */
1424 goog.dom.getPreviousNode = function(node) {
1425 if (!node) {
1426 return null;
1427 }
1428
1429 if (!node.previousSibling) {
1430 return node.parentNode;
1431 }
1432
1433 node = node.previousSibling;
1434 while (node && node.lastChild) {
1435 node = node.lastChild;
1436 }
1437
1438 return node;
1439 };
1440
1441
1442 /**
1443 * Whether the object looks like a DOM node.
1444 * @param {?} obj The object being tested for node likeness.
1445 * @return {boolean} Whether the object looks like a DOM node.
1446 */
1447 goog.dom.isNodeLike = function(obj) {
1448 return goog.isObject(obj) && obj.nodeType > 0;
1449 };
1450
1451
1452 /**
1453 * Whether the object looks like an Element.
1454 * @param {?} obj The object being tested for Element likeness.
1455 * @return {boolean} Whether the object looks like an Element.
1456 */
1457 goog.dom.isElement = function(obj) {
1458 return goog.isObject(obj) && obj.nodeType == goog.dom.NodeType.ELEMENT;
1459 };
1460
1461
1462 /**
1463 * Returns true if the specified value is a Window object. This includes the
1464 * global window for HTML pages, and iframe windows.
1465 * @param {?} obj Variable to test.
1466 * @return {boolean} Whether the variable is a window.
1467 */
1468 goog.dom.isWindow = function(obj) {
1469 return goog.isObject(obj) && obj['window'] == obj;
1470 };
1471
1472
1473 /**
1474 * Returns an element's parent, if it's an Element.
1475 * @param {Element} element The DOM element.
1476 * @return {Element} The parent, or null if not an Element.
1477 */
1478 goog.dom.getParentElement = function(element) {
1479 var parent;
1480 if (goog.dom.BrowserFeature.CAN_USE_PARENT_ELEMENT_PROPERTY) {
1481 var isIe9 = goog.userAgent.IE && goog.userAgent.isVersionOrHigher('9') &&
1482 !goog.userAgent.isVersionOrHigher('10');
1483 // SVG elements in IE9 can't use the parentElement property.
1484 // goog.global['SVGElement'] is not defined in IE9 quirks mode.
1485 if (!(isIe9 && goog.global['SVGElement'] &&
1486 element instanceof goog.global['SVGElement'])) {
1487 parent = element.parentElement;
1488 if (parent) {
1489 return parent;
1490 }
1491 }
1492 }
1493 parent = element.parentNode;
1494 return goog.dom.isElement(parent) ? /** @type {!Element} */ (parent) : null;
1495 };
1496
1497
1498 /**
1499 * Whether a node contains another node.
1500 * @param {?Node|undefined} parent The node that should contain the other node.
1501 * @param {?Node|undefined} descendant The node to test presence of.
1502 * @return {boolean} Whether the parent node contains the descendent node.
1503 */
1504 goog.dom.contains = function(parent, descendant) {
1505 if (!parent || !descendant) {
1506 return false;
1507 }
1508 // We use browser specific methods for this if available since it is faster
1509 // that way.
1510
1511 // IE DOM
1512 if (parent.contains && descendant.nodeType == goog.dom.NodeType.ELEMENT) {
1513 return parent == descendant || parent.contains(descendant);
1514 }
1515
1516 // W3C DOM Level 3
1517 if (typeof parent.compareDocumentPosition != 'undefined') {
1518 return parent == descendant ||
1519 Boolean(parent.compareDocumentPosition(descendant) & 16);
1520 }
1521
1522 // W3C DOM Level 1
1523 while (descendant && parent != descendant) {
1524 descendant = descendant.parentNode;
1525 }
1526 return descendant == parent;
1527 };
1528
1529
1530 /**
1531 * Compares the document order of two nodes, returning 0 if they are the same
1532 * node, a negative number if node1 is before node2, and a positive number if
1533 * node2 is before node1. Note that we compare the order the tags appear in the
1534 * document so in the tree <b><i>text</i></b> the B node is considered to be
1535 * before the I node.
1536 *
1537 * @param {Node} node1 The first node to compare.
1538 * @param {Node} node2 The second node to compare.
1539 * @return {number} 0 if the nodes are the same node, a negative number if node1
1540 * is before node2, and a positive number if node2 is before node1.
1541 */
1542 goog.dom.compareNodeOrder = function(node1, node2) {
1543 // Fall out quickly for equality.
1544 if (node1 == node2) {
1545 return 0;
1546 }
1547
1548 // Use compareDocumentPosition where available
1549 if (node1.compareDocumentPosition) {
1550 // 4 is the bitmask for FOLLOWS.
1551 return node1.compareDocumentPosition(node2) & 2 ? 1 : -1;
1552 }
1553
1554 // Special case for document nodes on IE 7 and 8.
1555 if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) {
1556 if (node1.nodeType == goog.dom.NodeType.DOCUMENT) {
1557 return -1;
1558 }
1559 if (node2.nodeType == goog.dom.NodeType.DOCUMENT) {
1560 return 1;
1561 }
1562 }
1563
1564 // Process in IE using sourceIndex - we check to see if the first node has
1565 // a source index or if its parent has one.
1566 if ('sourceIndex' in node1 ||
1567 (node1.parentNode && 'sourceIndex' in node1.parentNode)) {
1568 var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT;
1569 var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT;
1570
1571 if (isElement1 && isElement2) {
1572 return node1.sourceIndex - node2.sourceIndex;
1573 } else {
1574 var parent1 = node1.parentNode;
1575 var parent2 = node2.parentNode;
1576
1577 if (parent1 == parent2) {
1578 return goog.dom.compareSiblingOrder_(node1, node2);
1579 }
1580
1581 if (!isElement1 && goog.dom.contains(parent1, node2)) {
1582 return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2);
1583 }
1584
1585
1586 if (!isElement2 && goog.dom.contains(parent2, node1)) {
1587 return goog.dom.compareParentsDescendantNodeIe_(node2, node1);
1588 }
1589
1590 return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) -
1591 (isElement2 ? node2.sourceIndex : parent2.sourceIndex);
1592 }
1593 }
1594
1595 // For Safari, we compare ranges.
1596 var doc = goog.dom.getOwnerDocument(node1);
1597
1598 var range1, range2;
1599 range1 = doc.createRange();
1600 range1.selectNode(node1);
1601 range1.collapse(true);
1602
1603 range2 = doc.createRange();
1604 range2.selectNode(node2);
1605 range2.collapse(true);
1606
1607 return range1.compareBoundaryPoints(
1608 goog.global['Range'].START_TO_END, range2);
1609 };
1610
1611
1612 /**
1613 * Utility function to compare the position of two nodes, when
1614 * {@code textNode}'s parent is an ancestor of {@code node}. If this entry
1615 * condition is not met, this function will attempt to reference a null object.
1616 * @param {!Node} textNode The textNode to compare.
1617 * @param {Node} node The node to compare.
1618 * @return {number} -1 if node is before textNode, +1 otherwise.
1619 * @private
1620 */
1621 goog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) {
1622 var parent = textNode.parentNode;
1623 if (parent == node) {
1624 // If textNode is a child of node, then node comes first.
1625 return -1;
1626 }
1627 var sibling = node;
1628 while (sibling.parentNode != parent) {
1629 sibling = sibling.parentNode;
1630 }
1631 return goog.dom.compareSiblingOrder_(sibling, textNode);
1632 };
1633
1634
1635 /**
1636 * Utility function to compare the position of two nodes known to be non-equal
1637 * siblings.
1638 * @param {Node} node1 The first node to compare.
1639 * @param {!Node} node2 The second node to compare.
1640 * @return {number} -1 if node1 is before node2, +1 otherwise.
1641 * @private
1642 */
1643 goog.dom.compareSiblingOrder_ = function(node1, node2) {
1644 var s = node2;
1645 while ((s = s.previousSibling)) {
1646 if (s == node1) {
1647 // We just found node1 before node2.
1648 return -1;
1649 }
1650 }
1651
1652 // Since we didn't find it, node1 must be after node2.
1653 return 1;
1654 };
1655
1656
1657 /**
1658 * Find the deepest common ancestor of the given nodes.
1659 * @param {...Node} var_args The nodes to find a common ancestor of.
1660 * @return {Node} The common ancestor of the nodes, or null if there is none.
1661 * null will only be returned if two or more of the nodes are from different
1662 * documents.
1663 */
1664 goog.dom.findCommonAncestor = function(var_args) {
1665 var i, count = arguments.length;
1666 if (!count) {
1667 return null;
1668 } else if (count == 1) {
1669 return arguments[0];
1670 }
1671
1672 var paths = [];
1673 var minLength = Infinity;
1674 for (i = 0; i < count; i++) {
1675 // Compute the list of ancestors.
1676 var ancestors = [];
1677 var node = arguments[i];
1678 while (node) {
1679 ancestors.unshift(node);
1680 node = node.parentNode;
1681 }
1682
1683 // Save the list for comparison.
1684 paths.push(ancestors);
1685 minLength = Math.min(minLength, ancestors.length);
1686 }
1687 var output = null;
1688 for (i = 0; i < minLength; i++) {
1689 var first = paths[0][i];
1690 for (var j = 1; j < count; j++) {
1691 if (first != paths[j][i]) {
1692 return output;
1693 }
1694 }
1695 output = first;
1696 }
1697 return output;
1698 };
1699
1700
1701 /**
1702 * Returns the owner document for a node.
1703 * @param {Node|Window} node The node to get the document for.
1704 * @return {!Document} The document owning the node.
1705 */
1706 goog.dom.getOwnerDocument = function(node) {
1707 // TODO(nnaze): Update param signature to be non-nullable.
1708 goog.asserts.assert(node, 'Node cannot be null or undefined.');
1709 return /** @type {!Document} */ (
1710 node.nodeType == goog.dom.NodeType.DOCUMENT ? node : node.ownerDocument ||
1711 node.document);
1712 };
1713
1714
1715 /**
1716 * Cross-browser function for getting the document element of a frame or iframe.
1717 * @param {Element} frame Frame element.
1718 * @return {!Document} The frame content document.
1719 */
1720 goog.dom.getFrameContentDocument = function(frame) {
1721 return frame.contentDocument ||
1722 /** @type {!HTMLFrameElement} */ (frame).contentWindow.document;
1723 };
1724
1725
1726 /**
1727 * Cross-browser function for getting the window of a frame or iframe.
1728 * @param {Element} frame Frame element.
1729 * @return {Window} The window associated with the given frame, or null if none
1730 * exists.
1731 */
1732 goog.dom.getFrameContentWindow = function(frame) {
1733 try {
1734 return frame.contentWindow ||
1735 (frame.contentDocument ? goog.dom.getWindow(frame.contentDocument) :
1736 null);
1737 } catch (e) {
1738 // NOTE(user): In IE8, checking the contentWindow or contentDocument
1739 // properties will throw a "Unspecified Error" exception if the iframe is
1740 // not inserted in the DOM. If we get this we can be sure that no window
1741 // exists, so return null.
1742 }
1743 return null;
1744 };
1745
1746
1747 /**
1748 * Sets the text content of a node, with cross-browser support.
1749 * @param {Node} node The node to change the text content of.
1750 * @param {string|number} text The value that should replace the node's content.
1751 */
1752 goog.dom.setTextContent = function(node, text) {
1753 goog.asserts.assert(
1754 node != null,
1755 'goog.dom.setTextContent expects a non-null value for node');
1756
1757 if ('textContent' in node) {
1758 node.textContent = text;
1759 } else if (node.nodeType == goog.dom.NodeType.TEXT) {
1760 /** @type {!Text} */ (node).data = String(text);
1761 } else if (
1762 node.firstChild && node.firstChild.nodeType == goog.dom.NodeType.TEXT) {
1763 // If the first child is a text node we just change its data and remove the
1764 // rest of the children.
1765 while (node.lastChild != node.firstChild) {
1766 node.removeChild(node.lastChild);
1767 }
1768 /** @type {!Text} */ (node.firstChild).data = String(text);
1769 } else {
1770 goog.dom.removeChildren(node);
1771 var doc = goog.dom.getOwnerDocument(node);
1772 node.appendChild(doc.createTextNode(String(text)));
1773 }
1774 };
1775
1776
1777 /**
1778 * Gets the outerHTML of a node, which islike innerHTML, except that it
1779 * actually contains the HTML of the node itself.
1780 * @param {Element} element The element to get the HTML of.
1781 * @return {string} The outerHTML of the given element.
1782 */
1783 goog.dom.getOuterHtml = function(element) {
1784 goog.asserts.assert(
1785 element !== null,
1786 'goog.dom.getOuterHtml expects a non-null value for element');
1787 // IE, Opera and WebKit all have outerHTML.
1788 if ('outerHTML' in element) {
1789 return element.outerHTML;
1790 } else {
1791 var doc = goog.dom.getOwnerDocument(element);
1792 var div = goog.dom.createElement_(doc, goog.dom.TagName.DIV);
1793 div.appendChild(element.cloneNode(true));
1794 return div.innerHTML;
1795 }
1796 };
1797
1798
1799 /**
1800 * Finds the first descendant node that matches the filter function, using
1801 * a depth first search. This function offers the most general purpose way
1802 * of finding a matching element. You may also wish to consider
1803 * {@code goog.dom.query} which can express many matching criteria using
1804 * CSS selector expressions. These expressions often result in a more
1805 * compact representation of the desired result.
1806 * @see goog.dom.query
1807 *
1808 * @param {Node} root The root of the tree to search.
1809 * @param {function(Node) : boolean} p The filter function.
1810 * @return {Node|undefined} The found node or undefined if none is found.
1811 */
1812 goog.dom.findNode = function(root, p) {
1813 var rv = [];
1814 var found = goog.dom.findNodes_(root, p, rv, true);
1815 return found ? rv[0] : undefined;
1816 };
1817
1818
1819 /**
1820 * Finds all the descendant nodes that match the filter function, using a
1821 * a depth first search. This function offers the most general-purpose way
1822 * of finding a set of matching elements. You may also wish to consider
1823 * {@code goog.dom.query} which can express many matching criteria using
1824 * CSS selector expressions. These expressions often result in a more
1825 * compact representation of the desired result.
1826
1827 * @param {Node} root The root of the tree to search.
1828 * @param {function(Node) : boolean} p The filter function.
1829 * @return {!Array<!Node>} The found nodes or an empty array if none are found.
1830 */
1831 goog.dom.findNodes = function(root, p) {
1832 var rv = [];
1833 goog.dom.findNodes_(root, p, rv, false);
1834 return rv;
1835 };
1836
1837
1838 /**
1839 * Finds the first or all the descendant nodes that match the filter function,
1840 * using a depth first search.
1841 * @param {Node} root The root of the tree to search.
1842 * @param {function(Node) : boolean} p The filter function.
1843 * @param {!Array<!Node>} rv The found nodes are added to this array.
1844 * @param {boolean} findOne If true we exit after the first found node.
1845 * @return {boolean} Whether the search is complete or not. True in case findOne
1846 * is true and the node is found. False otherwise.
1847 * @private
1848 */
1849 goog.dom.findNodes_ = function(root, p, rv, findOne) {
1850 if (root != null) {
1851 var child = root.firstChild;
1852 while (child) {
1853 if (p(child)) {
1854 rv.push(child);
1855 if (findOne) {
1856 return true;
1857 }
1858 }
1859 if (goog.dom.findNodes_(child, p, rv, findOne)) {
1860 return true;
1861 }
1862 child = child.nextSibling;
1863 }
1864 }
1865 return false;
1866 };
1867
1868
1869 /**
1870 * Map of tags whose content to ignore when calculating text length.
1871 * @private {!Object<string, number>}
1872 * @const
1873 */
1874 goog.dom.TAGS_TO_IGNORE_ = {
1875 'SCRIPT': 1,
1876 'STYLE': 1,
1877 'HEAD': 1,
1878 'IFRAME': 1,
1879 'OBJECT': 1
1880 };
1881
1882
1883 /**
1884 * Map of tags which have predefined values with regard to whitespace.
1885 * @private {!Object<string, string>}
1886 * @const
1887 */
1888 goog.dom.PREDEFINED_TAG_VALUES_ = {
1889 'IMG': ' ',
1890 'BR': '\n'
1891 };
1892
1893
1894 /**
1895 * Returns true if the element has a tab index that allows it to receive
1896 * keyboard focus (tabIndex >= 0), false otherwise. Note that some elements
1897 * natively support keyboard focus, even if they have no tab index.
1898 * @param {!Element} element Element to check.
1899 * @return {boolean} Whether the element has a tab index that allows keyboard
1900 * focus.
1901 */
1902 goog.dom.isFocusableTabIndex = function(element) {
1903 return goog.dom.hasSpecifiedTabIndex_(element) &&
1904 goog.dom.isTabIndexFocusable_(element);
1905 };
1906
1907
1908 /**
1909 * Enables or disables keyboard focus support on the element via its tab index.
1910 * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true
1911 * (or elements that natively support keyboard focus, like form elements) can
1912 * receive keyboard focus. See http://go/tabindex for more info.
1913 * @param {Element} element Element whose tab index is to be changed.
1914 * @param {boolean} enable Whether to set or remove a tab index on the element
1915 * that supports keyboard focus.
1916 */
1917 goog.dom.setFocusableTabIndex = function(element, enable) {
1918 if (enable) {
1919 element.tabIndex = 0;
1920 } else {
1921 // Set tabIndex to -1 first, then remove it. This is a workaround for
1922 // Safari (confirmed in version 4 on Windows). When removing the attribute
1923 // without setting it to -1 first, the element remains keyboard focusable
1924 // despite not having a tabIndex attribute anymore.
1925 element.tabIndex = -1;
1926 element.removeAttribute('tabIndex'); // Must be camelCase!
1927 }
1928 };
1929
1930
1931 /**
1932 * Returns true if the element can be focused, i.e. it has a tab index that
1933 * allows it to receive keyboard focus (tabIndex >= 0), or it is an element
1934 * that natively supports keyboard focus.
1935 * @param {!Element} element Element to check.
1936 * @return {boolean} Whether the element allows keyboard focus.
1937 */
1938 goog.dom.isFocusable = function(element) {
1939 var focusable;
1940 // Some elements can have unspecified tab index and still receive focus.
1941 if (goog.dom.nativelySupportsFocus_(element)) {
1942 // Make sure the element is not disabled ...
1943 focusable = !element.disabled &&
1944 // ... and if a tab index is specified, it allows focus.
1945 (!goog.dom.hasSpecifiedTabIndex_(element) ||
1946 goog.dom.isTabIndexFocusable_(element));
1947 } else {
1948 focusable = goog.dom.isFocusableTabIndex(element);
1949 }
1950
1951 // IE requires elements to be visible in order to focus them.
1952 return focusable && goog.userAgent.IE ?
1953 goog.dom.hasNonZeroBoundingRect_(/** @type {!HTMLElement} */ (element)) :
1954 focusable;
1955 };
1956
1957
1958 /**
1959 * Returns true if the element has a specified tab index.
1960 * @param {!Element} element Element to check.
1961 * @return {boolean} Whether the element has a specified tab index.
1962 * @private
1963 */
1964 goog.dom.hasSpecifiedTabIndex_ = function(element) {
1965 // IE8 and below don't support hasAttribute(), instead check whether the
1966 // 'tabindex' attributeNode is specified. Otherwise check hasAttribute().
1967 if (goog.userAgent.IE && !goog.userAgent.isVersionOrHigher('9')) {
1968 var attrNode = element.getAttributeNode('tabindex'); // Must be lowercase!
1969 return goog.isDefAndNotNull(attrNode) && attrNode.specified;
1970 } else {
1971 return element.hasAttribute('tabindex');
1972 }
1973 };
1974
1975
1976 /**
1977 * Returns true if the element's tab index allows the element to be focused.
1978 * @param {!Element} element Element to check.
1979 * @return {boolean} Whether the element's tab index allows focus.
1980 * @private
1981 */
1982 goog.dom.isTabIndexFocusable_ = function(element) {
1983 var index = /** @type {!HTMLElement} */ (element).tabIndex;
1984 // NOTE: IE9 puts tabIndex in 16-bit int, e.g. -2 is 65534.
1985 return goog.isNumber(index) && index >= 0 && index < 32768;
1986 };
1987
1988
1989 /**
1990 * Returns true if the element is focusable even when tabIndex is not set.
1991 * @param {!Element} element Element to check.
1992 * @return {boolean} Whether the element natively supports focus.
1993 * @private
1994 */
1995 goog.dom.nativelySupportsFocus_ = function(element) {
1996 return element.tagName == goog.dom.TagName.A ||
1997 element.tagName == goog.dom.TagName.INPUT ||
1998 element.tagName == goog.dom.TagName.TEXTAREA ||
1999 element.tagName == goog.dom.TagName.SELECT ||
2000 element.tagName == goog.dom.TagName.BUTTON;
2001 };
2002
2003
2004 /**
2005 * Returns true if the element has a bounding rectangle that would be visible
2006 * (i.e. its width and height are greater than zero).
2007 * @param {!HTMLElement} element Element to check.
2008 * @return {boolean} Whether the element has a non-zero bounding rectangle.
2009 * @private
2010 */
2011 goog.dom.hasNonZeroBoundingRect_ = function(element) {
2012 var rect;
2013 if (!goog.isFunction(element['getBoundingClientRect']) ||
2014 // In IE, getBoundingClientRect throws on detached nodes.
2015 (goog.userAgent.IE && element.parentElement == null)) {
2016 rect = {'height': element.offsetHeight, 'width': element.offsetWidth};
2017 } else {
2018 rect = element.getBoundingClientRect();
2019 }
2020 return goog.isDefAndNotNull(rect) && rect.height > 0 && rect.width > 0;
2021 };
2022
2023
2024 /**
2025 * Returns the text content of the current node, without markup and invisible
2026 * symbols. New lines are stripped and whitespace is collapsed,
2027 * such that each character would be visible.
2028 *
2029 * In browsers that support it, innerText is used. Other browsers attempt to
2030 * simulate it via node traversal. Line breaks are canonicalized in IE.
2031 *
2032 * @param {Node} node The node from which we are getting content.
2033 * @return {string} The text content.
2034 */
2035 goog.dom.getTextContent = function(node) {
2036 var textContent;
2037 // Note(arv): IE9, Opera, and Safari 3 support innerText but they include
2038 // text nodes in script tags. So we revert to use a user agent test here.
2039 if (goog.dom.BrowserFeature.CAN_USE_INNER_TEXT && node !== null &&
2040 ('innerText' in node)) {
2041 textContent = goog.string.canonicalizeNewlines(node.innerText);
2042 // Unfortunately .innerText() returns text with &shy; symbols
2043 // We need to filter it out and then remove duplicate whitespaces
2044 } else {
2045 var buf = [];
2046 goog.dom.getTextContent_(node, buf, true);
2047 textContent = buf.join('');
2048 }
2049
2050 // Strip &shy; entities. goog.format.insertWordBreaks inserts them in Opera.
2051 textContent = textContent.replace(/ \xAD /g, ' ').replace(/\xAD/g, '');
2052 // Strip &#8203; entities. goog.format.insertWordBreaks inserts them in IE8.
2053 textContent = textContent.replace(/\u200B/g, '');
2054
2055 // Skip this replacement on old browsers with working innerText, which
2056 // automatically turns &nbsp; into ' ' and / +/ into ' ' when reading
2057 // innerText.
2058 if (!goog.dom.BrowserFeature.CAN_USE_INNER_TEXT) {
2059 textContent = textContent.replace(/ +/g, ' ');
2060 }
2061 if (textContent != ' ') {
2062 textContent = textContent.replace(/^\s*/, '');
2063 }
2064
2065 return textContent;
2066 };
2067
2068
2069 /**
2070 * Returns the text content of the current node, without markup.
2071 *
2072 * Unlike {@code getTextContent} this method does not collapse whitespaces
2073 * or normalize lines breaks.
2074 *
2075 * @param {Node} node The node from which we are getting content.
2076 * @return {string} The raw text content.
2077 */
2078 goog.dom.getRawTextContent = function(node) {
2079 var buf = [];
2080 goog.dom.getTextContent_(node, buf, false);
2081
2082 return buf.join('');
2083 };
2084
2085
2086 /**
2087 * Recursive support function for text content retrieval.
2088 *
2089 * @param {Node} node The node from which we are getting content.
2090 * @param {Array<string>} buf string buffer.
2091 * @param {boolean} normalizeWhitespace Whether to normalize whitespace.
2092 * @private
2093 */
2094 goog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) {
2095 if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) {
2096 // ignore certain tags
2097 } else if (node.nodeType == goog.dom.NodeType.TEXT) {
2098 if (normalizeWhitespace) {
2099 buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, ''));
2100 } else {
2101 buf.push(node.nodeValue);
2102 }
2103 } else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {
2104 buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]);
2105 } else {
2106 var child = node.firstChild;
2107 while (child) {
2108 goog.dom.getTextContent_(child, buf, normalizeWhitespace);
2109 child = child.nextSibling;
2110 }
2111 }
2112 };
2113
2114
2115 /**
2116 * Returns the text length of the text contained in a node, without markup. This
2117 * is equivalent to the selection length if the node was selected, or the number
2118 * of cursor movements to traverse the node. Images & BRs take one space. New
2119 * lines are ignored.
2120 *
2121 * @param {Node} node The node whose text content length is being calculated.
2122 * @return {number} The length of {@code node}'s text content.
2123 */
2124 goog.dom.getNodeTextLength = function(node) {
2125 return goog.dom.getTextContent(node).length;
2126 };
2127
2128
2129 /**
2130 * Returns the text offset of a node relative to one of its ancestors. The text
2131 * length is the same as the length calculated by goog.dom.getNodeTextLength.
2132 *
2133 * @param {Node} node The node whose offset is being calculated.
2134 * @param {Node=} opt_offsetParent The node relative to which the offset will
2135 * be calculated. Defaults to the node's owner document's body.
2136 * @return {number} The text offset.
2137 */
2138 goog.dom.getNodeTextOffset = function(node, opt_offsetParent) {
2139 var root = opt_offsetParent || goog.dom.getOwnerDocument(node).body;
2140 var buf = [];
2141 while (node && node != root) {
2142 var cur = node;
2143 while ((cur = cur.previousSibling)) {
2144 buf.unshift(goog.dom.getTextContent(cur));
2145 }
2146 node = node.parentNode;
2147 }
2148 // Trim left to deal with FF cases when there might be line breaks and empty
2149 // nodes at the front of the text
2150 return goog.string.trimLeft(buf.join('')).replace(/ +/g, ' ').length;
2151 };
2152
2153
2154 /**
2155 * Returns the node at a given offset in a parent node. If an object is
2156 * provided for the optional third parameter, the node and the remainder of the
2157 * offset will stored as properties of this object.
2158 * @param {Node} parent The parent node.
2159 * @param {number} offset The offset into the parent node.
2160 * @param {Object=} opt_result Object to be used to store the return value. The
2161 * return value will be stored in the form {node: Node, remainder: number}
2162 * if this object is provided.
2163 * @return {Node} The node at the given offset.
2164 */
2165 goog.dom.getNodeAtOffset = function(parent, offset, opt_result) {
2166 var stack = [parent], pos = 0, cur = null;
2167 while (stack.length > 0 && pos < offset) {
2168 cur = stack.pop();
2169 if (cur.nodeName in goog.dom.TAGS_TO_IGNORE_) {
2170 // ignore certain tags
2171 } else if (cur.nodeType == goog.dom.NodeType.TEXT) {
2172 var text = cur.nodeValue.replace(/(\r\n|\r|\n)/g, '').replace(/ +/g, ' ');
2173 pos += text.length;
2174 } else if (cur.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {
2175 pos += goog.dom.PREDEFINED_TAG_VALUES_[cur.nodeName].length;
2176 } else {
2177 for (var i = cur.childNodes.length - 1; i >= 0; i--) {
2178 stack.push(cur.childNodes[i]);
2179 }
2180 }
2181 }
2182 if (goog.isObject(opt_result)) {
2183 opt_result.remainder = cur ? cur.nodeValue.length + offset - pos - 1 : 0;
2184 opt_result.node = cur;
2185 }
2186
2187 return cur;
2188 };
2189
2190
2191 /**
2192 * Returns true if the object is a {@code NodeList}. To qualify as a NodeList,
2193 * the object must have a numeric length property and an item function (which
2194 * has type 'string' on IE for some reason).
2195 * @param {Object} val Object to test.
2196 * @return {boolean} Whether the object is a NodeList.
2197 */
2198 goog.dom.isNodeList = function(val) {
2199 // TODO(attila): Now the isNodeList is part of goog.dom we can use
2200 // goog.userAgent to make this simpler.
2201 // A NodeList must have a length property of type 'number' on all platforms.
2202 if (val && typeof val.length == 'number') {
2203 // A NodeList is an object everywhere except Safari, where it's a function.
2204 if (goog.isObject(val)) {
2205 // A NodeList must have an item function (on non-IE platforms) or an item
2206 // property of type 'string' (on IE).
2207 return typeof val.item == 'function' || typeof val.item == 'string';
2208 } else if (goog.isFunction(val)) {
2209 // On Safari, a NodeList is a function with an item property that is also
2210 // a function.
2211 return typeof val.item == 'function';
2212 }
2213 }
2214
2215 // Not a NodeList.
2216 return false;
2217 };
2218
2219
2220 /**
2221 * Walks up the DOM hierarchy returning the first ancestor that has the passed
2222 * tag name and/or class name. If the passed element matches the specified
2223 * criteria, the element itself is returned.
2224 * @param {Node} element The DOM node to start with.
2225 * @param {?(goog.dom.TagName<T>|string)=} opt_tag The tag name to match (or
2226 * null/undefined to match only based on class name).
2227 * @param {?string=} opt_class The class name to match (or null/undefined to
2228 * match only based on tag name).
2229 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
2230 * dom.
2231 * @return {?R} The first ancestor that matches the passed criteria, or
2232 * null if no match is found. The return type is {?Element} if opt_tag is
2233 * not a member of goog.dom.TagName or a more specific type if it is (e.g.
2234 * {?HTMLAnchorElement} for goog.dom.TagName.A).
2235 * @template T
2236 * @template R := cond(isUnknown(T), 'Element', T) =:
2237 */
2238 goog.dom.getAncestorByTagNameAndClass = function(
2239 element, opt_tag, opt_class, opt_maxSearchSteps) {
2240 if (!opt_tag && !opt_class) {
2241 return null;
2242 }
2243 var tagName = opt_tag ? String(opt_tag).toUpperCase() : null;
2244 return /** @type {Element} */ (goog.dom.getAncestor(element, function(node) {
2245 return (!tagName || node.nodeName == tagName) &&
2246 (!opt_class ||
2247 goog.isString(node.className) &&
2248 goog.array.contains(node.className.split(/\s+/), opt_class));
2249 }, true, opt_maxSearchSteps));
2250 };
2251
2252
2253 /**
2254 * Walks up the DOM hierarchy returning the first ancestor that has the passed
2255 * class name. If the passed element matches the specified criteria, the
2256 * element itself is returned.
2257 * @param {Node} element The DOM node to start with.
2258 * @param {string} className The class name to match.
2259 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
2260 * dom.
2261 * @return {Element} The first ancestor that matches the passed criteria, or
2262 * null if none match.
2263 */
2264 goog.dom.getAncestorByClass = function(element, className, opt_maxSearchSteps) {
2265 return goog.dom.getAncestorByTagNameAndClass(
2266 element, null, className, opt_maxSearchSteps);
2267 };
2268
2269
2270 /**
2271 * Walks up the DOM hierarchy returning the first ancestor that passes the
2272 * matcher function.
2273 * @param {Node} element The DOM node to start with.
2274 * @param {function(Node) : boolean} matcher A function that returns true if the
2275 * passed node matches the desired criteria.
2276 * @param {boolean=} opt_includeNode If true, the node itself is included in
2277 * the search (the first call to the matcher will pass startElement as
2278 * the node to test).
2279 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
2280 * dom.
2281 * @return {Node} DOM node that matched the matcher, or null if there was
2282 * no match.
2283 */
2284 goog.dom.getAncestor = function(
2285 element, matcher, opt_includeNode, opt_maxSearchSteps) {
2286 if (element && !opt_includeNode) {
2287 element = element.parentNode;
2288 }
2289 var steps = 0;
2290 while (element &&
2291 (opt_maxSearchSteps == null || steps <= opt_maxSearchSteps)) {
2292 goog.asserts.assert(element.name != 'parentNode');
2293 if (matcher(element)) {
2294 return element;
2295 }
2296 element = element.parentNode;
2297 steps++;
2298 }
2299 // Reached the root of the DOM without a match
2300 return null;
2301 };
2302
2303
2304 /**
2305 * Determines the active element in the given document.
2306 * @param {Document} doc The document to look in.
2307 * @return {Element} The active element.
2308 */
2309 goog.dom.getActiveElement = function(doc) {
2310 try {
2311 return doc && doc.activeElement;
2312 } catch (e) {
2313 // NOTE(nicksantos): Sometimes, evaluating document.activeElement in IE
2314 // throws an exception. I'm not 100% sure why, but I suspect it chokes
2315 // on document.activeElement if the activeElement has been recently
2316 // removed from the DOM by a JS operation.
2317 //
2318 // We assume that an exception here simply means
2319 // "there is no active element."
2320 }
2321
2322 return null;
2323 };
2324
2325
2326 /**
2327 * Gives the current devicePixelRatio.
2328 *
2329 * By default, this is the value of window.devicePixelRatio (which should be
2330 * preferred if present).
2331 *
2332 * If window.devicePixelRatio is not present, the ratio is calculated with
2333 * window.matchMedia, if present. Otherwise, gives 1.0.
2334 *
2335 * Some browsers (including Chrome) consider the browser zoom level in the pixel
2336 * ratio, so the value may change across multiple calls.
2337 *
2338 * @return {number} The number of actual pixels per virtual pixel.
2339 */
2340 goog.dom.getPixelRatio = function() {
2341 var win = goog.dom.getWindow();
2342 if (goog.isDef(win.devicePixelRatio)) {
2343 return win.devicePixelRatio;
2344 } else if (win.matchMedia) {
2345 // Should be for IE10 and FF6-17 (this basically clamps to lower)
2346 // Note that the order of these statements is important
2347 return goog.dom.matchesPixelRatio_(3) || goog.dom.matchesPixelRatio_(2) ||
2348 goog.dom.matchesPixelRatio_(1.5) || goog.dom.matchesPixelRatio_(1) ||
2349 .75;
2350 }
2351 return 1;
2352 };
2353
2354
2355 /**
2356 * Calculates a mediaQuery to check if the current device supports the
2357 * given actual to virtual pixel ratio.
2358 * @param {number} pixelRatio The ratio of actual pixels to virtual pixels.
2359 * @return {number} pixelRatio if applicable, otherwise 0.
2360 * @private
2361 */
2362 goog.dom.matchesPixelRatio_ = function(pixelRatio) {
2363 var win = goog.dom.getWindow();
2364 /**
2365 * Due to the 1:96 fixed ratio of CSS in to CSS px, 1dppx is equivalent to
2366 * 96dpi.
2367 * @const {number}
2368 */
2369 var dpiPerDppx = 96;
2370 var query =
2371 // FF16-17
2372 '(min-resolution: ' + pixelRatio + 'dppx),' +
2373 // FF6-15
2374 '(min--moz-device-pixel-ratio: ' + pixelRatio + '),' +
2375 // IE10 (this works for the two browsers above too but I don't want to
2376 // trust the 1:96 fixed ratio magic)
2377 '(min-resolution: ' + (pixelRatio * dpiPerDppx) + 'dpi)';
2378 return win.matchMedia(query).matches ? pixelRatio : 0;
2379 };
2380
2381
2382 /**
2383 * Gets '2d' context of a canvas. Shortcut for canvas.getContext('2d') with a
2384 * type information.
2385 * @param {!HTMLCanvasElement} canvas
2386 * @return {!CanvasRenderingContext2D}
2387 */
2388 goog.dom.getCanvasContext2D = function(canvas) {
2389 return /** @type {!CanvasRenderingContext2D} */ (canvas.getContext('2d'));
2390 };
2391
2392
2393
2394 /**
2395 * Create an instance of a DOM helper with a new document object.
2396 * @param {Document=} opt_document Document object to associate with this
2397 * DOM helper.
2398 * @constructor
2399 */
2400 goog.dom.DomHelper = function(opt_document) {
2401 /**
2402 * Reference to the document object to use
2403 * @type {!Document}
2404 * @private
2405 */
2406 this.document_ = opt_document || goog.global.document || document;
2407 };
2408
2409
2410 /**
2411 * Gets the dom helper object for the document where the element resides.
2412 * @param {Node=} opt_node If present, gets the DomHelper for this node.
2413 * @return {!goog.dom.DomHelper} The DomHelper.
2414 */
2415 goog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper;
2416
2417
2418 /**
2419 * Sets the document object.
2420 * @param {!Document} document Document object.
2421 */
2422 goog.dom.DomHelper.prototype.setDocument = function(document) {
2423 this.document_ = document;
2424 };
2425
2426
2427 /**
2428 * Gets the document object being used by the dom library.
2429 * @return {!Document} Document object.
2430 */
2431 goog.dom.DomHelper.prototype.getDocument = function() {
2432 return this.document_;
2433 };
2434
2435
2436 /**
2437 * Alias for {@code getElementById}. If a DOM node is passed in then we just
2438 * return that.
2439 * @param {string|Element} element Element ID or a DOM node.
2440 * @return {Element} The element with the given ID, or the node passed in.
2441 */
2442 goog.dom.DomHelper.prototype.getElement = function(element) {
2443 return goog.dom.getElementHelper_(this.document_, element);
2444 };
2445
2446
2447 /**
2448 * Gets an element by id, asserting that the element is found.
2449 *
2450 * This is used when an element is expected to exist, and should fail with
2451 * an assertion error if it does not (if assertions are enabled).
2452 *
2453 * @param {string} id Element ID.
2454 * @return {!Element} The element with the given ID, if it exists.
2455 */
2456 goog.dom.DomHelper.prototype.getRequiredElement = function(id) {
2457 return goog.dom.getRequiredElementHelper_(this.document_, id);
2458 };
2459
2460
2461 /**
2462 * Alias for {@code getElement}.
2463 * @param {string|Element} element Element ID or a DOM node.
2464 * @return {Element} The element with the given ID, or the node passed in.
2465 * @deprecated Use {@link goog.dom.DomHelper.prototype.getElement} instead.
2466 */
2467 goog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement;
2468
2469
2470 /**
2471 * Gets elements by tag name.
2472 * @param {!goog.dom.TagName<T>} tagName
2473 * @param {(!Document|!Element)=} opt_parent Parent element or document where to
2474 * look for elements. Defaults to document of this DomHelper.
2475 * @return {!NodeList<R>} List of elements. The members of the list are
2476 * {!Element} if tagName is not a member of goog.dom.TagName or more
2477 * specific types if it is (e.g. {!HTMLAnchorElement} for
2478 * goog.dom.TagName.A).
2479 * @template T
2480 * @template R := cond(isUnknown(T), 'Element', T) =:
2481 */
2482 goog.dom.DomHelper.prototype.getElementsByTagName =
2483 function(tagName, opt_parent) {
2484 var parent = opt_parent || this.document_;
2485 return parent.getElementsByTagName(String(tagName));
2486 };
2487
2488
2489 /**
2490 * Looks up elements by both tag and class name, using browser native functions
2491 * ({@code querySelectorAll}, {@code getElementsByTagName} or
2492 * {@code getElementsByClassName}) where possible. The returned array is a live
2493 * NodeList or a static list depending on the code path taken.
2494 *
2495 * @see goog.dom.query
2496 *
2497 * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name or * for all
2498 * tags.
2499 * @param {?string=} opt_class Optional class name.
2500 * @param {(Document|Element)=} opt_el Optional element to look in.
2501 * @return {!IArrayLike<R>} Array-like list of elements (only a length property
2502 * and numerical indices are guaranteed to exist). The members of the array
2503 * are {!Element} if opt_tag is not a member of goog.dom.TagName or more
2504 * specific types if it is (e.g. {!HTMLAnchorElement} for
2505 * goog.dom.TagName.A).
2506 * @template T
2507 * @template R := cond(isUnknown(T), 'Element', T) =:
2508 */
2509 goog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(
2510 opt_tag, opt_class, opt_el) {
2511 return goog.dom.getElementsByTagNameAndClass_(
2512 this.document_, opt_tag, opt_class, opt_el);
2513 };
2514
2515
2516 /**
2517 * Gets the first element matching the tag and the class.
2518 *
2519 * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.
2520 * @param {?string=} opt_class Optional class name.
2521 * @param {(Document|Element)=} opt_el Optional element to look in.
2522 * @return {?R} Reference to a DOM node. The return type is {?Element} if
2523 * tagName is a string or a more specific type if it is a member of
2524 * goog.dom.TagName (e.g. {?HTMLAnchorElement} for goog.dom.TagName.A).
2525 * @template T
2526 * @template R := cond(isUnknown(T), 'Element', T) =:
2527 */
2528 goog.dom.DomHelper.prototype.getElementByTagNameAndClass = function(
2529 opt_tag, opt_class, opt_el) {
2530 return goog.dom.getElementByTagNameAndClass_(
2531 this.document_, opt_tag, opt_class, opt_el);
2532 };
2533
2534
2535 /**
2536 * Returns an array of all the elements with the provided className.
2537 * @see {goog.dom.query}
2538 * @param {string} className the name of the class to look for.
2539 * @param {Element|Document=} opt_el Optional element to look in.
2540 * @return {!IArrayLike<!Element>} The items found with the class name provided.
2541 */
2542 goog.dom.DomHelper.prototype.getElementsByClass = function(className, opt_el) {
2543 var doc = opt_el || this.document_;
2544 return goog.dom.getElementsByClass(className, doc);
2545 };
2546
2547
2548 /**
2549 * Returns the first element we find matching the provided class name.
2550 * @see {goog.dom.query}
2551 * @param {string} className the name of the class to look for.
2552 * @param {(Element|Document)=} opt_el Optional element to look in.
2553 * @return {Element} The first item found with the class name provided.
2554 */
2555 goog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) {
2556 var doc = opt_el || this.document_;
2557 return goog.dom.getElementByClass(className, doc);
2558 };
2559
2560
2561 /**
2562 * Ensures an element with the given className exists, and then returns the
2563 * first element with the provided className.
2564 * @see {goog.dom.query}
2565 * @param {string} className the name of the class to look for.
2566 * @param {(!Element|!Document)=} opt_root Optional element or document to look
2567 * in.
2568 * @return {!Element} The first item found with the class name provided.
2569 * @throws {goog.asserts.AssertionError} Thrown if no element is found.
2570 */
2571 goog.dom.DomHelper.prototype.getRequiredElementByClass = function(
2572 className, opt_root) {
2573 var root = opt_root || this.document_;
2574 return goog.dom.getRequiredElementByClass(className, root);
2575 };
2576
2577
2578 /**
2579 * Alias for {@code getElementsByTagNameAndClass}.
2580 * @deprecated Use DomHelper getElementsByTagNameAndClass.
2581 * @see goog.dom.query
2582 *
2583 * @param {(string|?goog.dom.TagName<T>)=} opt_tag Element tag name.
2584 * @param {?string=} opt_class Optional class name.
2585 * @param {Element=} opt_el Optional element to look in.
2586 * @return {!IArrayLike<R>} Array-like list of elements (only a length property
2587 * and numerical indices are guaranteed to exist). The members of the array
2588 * are {!Element} if opt_tag is a string or more specific types if it is
2589 * a member of goog.dom.TagName (e.g. {!HTMLAnchorElement} for
2590 * goog.dom.TagName.A).
2591 * @template T
2592 * @template R := cond(isUnknown(T), 'Element', T) =:
2593 */
2594 goog.dom.DomHelper.prototype.$$ =
2595 goog.dom.DomHelper.prototype.getElementsByTagNameAndClass;
2596
2597
2598 /**
2599 * Sets a number of properties on a node.
2600 * @param {Element} element DOM node to set properties on.
2601 * @param {Object} properties Hash of property:value pairs.
2602 */
2603 goog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties;
2604
2605
2606 /**
2607 * Gets the dimensions of the viewport.
2608 * @param {Window=} opt_window Optional window element to test. Defaults to
2609 * the window of the Dom Helper.
2610 * @return {!goog.math.Size} Object with values 'width' and 'height'.
2611 */
2612 goog.dom.DomHelper.prototype.getViewportSize = function(opt_window) {
2613 // TODO(arv): This should not take an argument. That breaks the rule of a
2614 // a DomHelper representing a single frame/window/document.
2615 return goog.dom.getViewportSize(opt_window || this.getWindow());
2616 };
2617
2618
2619 /**
2620 * Calculates the height of the document.
2621 *
2622 * @return {number} The height of the document.
2623 */
2624 goog.dom.DomHelper.prototype.getDocumentHeight = function() {
2625 return goog.dom.getDocumentHeight_(this.getWindow());
2626 };
2627
2628
2629 /**
2630 * Typedef for use with goog.dom.createDom and goog.dom.append.
2631 * @typedef {Object|string|Array|NodeList}
2632 */
2633 goog.dom.Appendable;
2634
2635
2636 /**
2637 * Returns a dom node with a set of attributes. This function accepts varargs
2638 * for subsequent nodes to be added. Subsequent nodes will be added to the
2639 * first node as childNodes.
2640 *
2641 * So:
2642 * <code>createDom(goog.dom.TagName.DIV, null, createDom(goog.dom.TagName.P),
2643 * createDom(goog.dom.TagName.P));</code> would return a div with two child
2644 * paragraphs
2645 *
2646 * An easy way to move all child nodes of an existing element to a new parent
2647 * element is:
2648 * <code>createDom(goog.dom.TagName.DIV, null, oldElement.childNodes);</code>
2649 * which will remove all child nodes from the old element and add them as
2650 * child nodes of the new DIV.
2651 *
2652 * @param {string|!goog.dom.TagName<T>} tagName Tag to create.
2653 * @param {?Object|?Array<string>|string=} opt_attributes If object, then a map
2654 * of name-value pairs for attributes. If a string, then this is the
2655 * className of the new element. If an array, the elements will be joined
2656 * together as the className of the new element.
2657 * @param {...goog.dom.Appendable} var_args Further DOM nodes or
2658 * strings for text nodes. If one of the var_args is an array or
2659 * NodeList, its elements will be added as childNodes instead.
2660 * @return {R} Reference to a DOM node. The return type is {!Element} if tagName
2661 * is a string or a more specific type if it is a member of
2662 * goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).
2663 * @template T
2664 * @template R := cond(isUnknown(T), 'Element', T) =:
2665 */
2666 goog.dom.DomHelper.prototype.createDom = function(
2667 tagName, opt_attributes, var_args) {
2668 return goog.dom.createDom_(this.document_, arguments);
2669 };
2670
2671
2672 /**
2673 * Alias for {@code createDom}.
2674 * @param {string|!goog.dom.TagName<T>} tagName Tag to create.
2675 * @param {?Object|?Array<string>|string=} opt_attributes If object, then a map
2676 * of name-value pairs for attributes. If a string, then this is the
2677 * className of the new element. If an array, the elements will be joined
2678 * together as the className of the new element.
2679 * @param {...goog.dom.Appendable} var_args Further DOM nodes or strings for
2680 * text nodes. If one of the var_args is an array, its children will be
2681 * added as childNodes instead.
2682 * @return {R} Reference to a DOM node. The return type is {!Element} if tagName
2683 * is a string or a more specific type if it is a member of
2684 * goog.dom.TagName (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).
2685 * @template T
2686 * @template R := cond(isUnknown(T), 'Element', T) =:
2687 * @deprecated Use {@link goog.dom.DomHelper.prototype.createDom} instead.
2688 */
2689 goog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom;
2690
2691
2692 /**
2693 * Creates a new element.
2694 * @param {string|!goog.dom.TagName<T>} name Tag to create.
2695 * @return {R} The new element. The return type is {!Element} if name is
2696 * a string or a more specific type if it is a member of goog.dom.TagName
2697 * (e.g. {!HTMLAnchorElement} for goog.dom.TagName.A).
2698 * @template T
2699 * @template R := cond(isUnknown(T), 'Element', T) =:
2700 */
2701 goog.dom.DomHelper.prototype.createElement = function(name) {
2702 return goog.dom.createElement_(this.document_, name);
2703 };
2704
2705
2706 /**
2707 * Creates a new text node.
2708 * @param {number|string} content Content.
2709 * @return {!Text} The new text node.
2710 */
2711 goog.dom.DomHelper.prototype.createTextNode = function(content) {
2712 return this.document_.createTextNode(String(content));
2713 };
2714
2715
2716 /**
2717 * Create a table.
2718 * @param {number} rows The number of rows in the table. Must be >= 1.
2719 * @param {number} columns The number of columns in the table. Must be >= 1.
2720 * @param {boolean=} opt_fillWithNbsp If true, fills table entries with
2721 * {@code goog.string.Unicode.NBSP} characters.
2722 * @return {!HTMLElement} The created table.
2723 */
2724 goog.dom.DomHelper.prototype.createTable = function(
2725 rows, columns, opt_fillWithNbsp) {
2726 return goog.dom.createTable_(
2727 this.document_, rows, columns, !!opt_fillWithNbsp);
2728 };
2729
2730
2731 /**
2732 * Converts an HTML into a node or a document fragment. A single Node is used if
2733 * {@code html} only generates a single node. If {@code html} generates multiple
2734 * nodes then these are put inside a {@code DocumentFragment}. This is a safe
2735 * version of {@code goog.dom.DomHelper#htmlToDocumentFragment} which is now
2736 * deleted.
2737 * @param {!goog.html.SafeHtml} html The HTML markup to convert.
2738 * @return {!Node} The resulting node.
2739 */
2740 goog.dom.DomHelper.prototype.safeHtmlToNode = function(html) {
2741 return goog.dom.safeHtmlToNode_(this.document_, html);
2742 };
2743
2744
2745 /**
2746 * Returns true if the browser is in "CSS1-compatible" (standards-compliant)
2747 * mode, false otherwise.
2748 * @return {boolean} True if in CSS1-compatible mode.
2749 */
2750 goog.dom.DomHelper.prototype.isCss1CompatMode = function() {
2751 return goog.dom.isCss1CompatMode_(this.document_);
2752 };
2753
2754
2755 /**
2756 * Gets the window object associated with the document.
2757 * @return {!Window} The window associated with the given document.
2758 */
2759 goog.dom.DomHelper.prototype.getWindow = function() {
2760 return goog.dom.getWindow_(this.document_);
2761 };
2762
2763
2764 /**
2765 * Gets the document scroll element.
2766 * @return {!Element} Scrolling element.
2767 */
2768 goog.dom.DomHelper.prototype.getDocumentScrollElement = function() {
2769 return goog.dom.getDocumentScrollElement_(this.document_);
2770 };
2771
2772
2773 /**
2774 * Gets the document scroll distance as a coordinate object.
2775 * @return {!goog.math.Coordinate} Object with properties 'x' and 'y'.
2776 */
2777 goog.dom.DomHelper.prototype.getDocumentScroll = function() {
2778 return goog.dom.getDocumentScroll_(this.document_);
2779 };
2780
2781
2782 /**
2783 * Determines the active element in the given document.
2784 * @param {Document=} opt_doc The document to look in.
2785 * @return {Element} The active element.
2786 */
2787 goog.dom.DomHelper.prototype.getActiveElement = function(opt_doc) {
2788 return goog.dom.getActiveElement(opt_doc || this.document_);
2789 };
2790
2791
2792 /**
2793 * Appends a child to a node.
2794 * @param {Node} parent Parent.
2795 * @param {Node} child Child.
2796 */
2797 goog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild;
2798
2799
2800 /**
2801 * Appends a node with text or other nodes.
2802 * @param {!Node} parent The node to append nodes to.
2803 * @param {...goog.dom.Appendable} var_args The things to append to the node.
2804 * If this is a Node it is appended as is.
2805 * If this is a string then a text node is appended.
2806 * If this is an array like object then fields 0 to length - 1 are appended.
2807 */
2808 goog.dom.DomHelper.prototype.append = goog.dom.append;
2809
2810
2811 /**
2812 * Determines if the given node can contain children, intended to be used for
2813 * HTML generation.
2814 *
2815 * @param {Node} node The node to check.
2816 * @return {boolean} Whether the node can contain children.
2817 */
2818 goog.dom.DomHelper.prototype.canHaveChildren = goog.dom.canHaveChildren;
2819
2820
2821 /**
2822 * Removes all the child nodes on a DOM node.
2823 * @param {Node} node Node to remove children from.
2824 */
2825 goog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren;
2826
2827
2828 /**
2829 * Inserts a new node before an existing reference node (i.e., as the previous
2830 * sibling). If the reference node has no parent, then does nothing.
2831 * @param {Node} newNode Node to insert.
2832 * @param {Node} refNode Reference node to insert before.
2833 */
2834 goog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore;
2835
2836
2837 /**
2838 * Inserts a new node after an existing reference node (i.e., as the next
2839 * sibling). If the reference node has no parent, then does nothing.
2840 * @param {Node} newNode Node to insert.
2841 * @param {Node} refNode Reference node to insert after.
2842 */
2843 goog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter;
2844
2845
2846 /**
2847 * Insert a child at a given index. If index is larger than the number of child
2848 * nodes that the parent currently has, the node is inserted as the last child
2849 * node.
2850 * @param {Element} parent The element into which to insert the child.
2851 * @param {Node} child The element to insert.
2852 * @param {number} index The index at which to insert the new child node. Must
2853 * not be negative.
2854 */
2855 goog.dom.DomHelper.prototype.insertChildAt = goog.dom.insertChildAt;
2856
2857
2858 /**
2859 * Removes a node from its parent.
2860 * @param {Node} node The node to remove.
2861 * @return {Node} The node removed if removed; else, null.
2862 */
2863 goog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode;
2864
2865
2866 /**
2867 * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no
2868 * parent.
2869 * @param {Node} newNode Node to insert.
2870 * @param {Node} oldNode Node to replace.
2871 */
2872 goog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode;
2873
2874
2875 /**
2876 * Flattens an element. That is, removes it and replace it with its children.
2877 * @param {Element} element The element to flatten.
2878 * @return {Element|undefined} The original element, detached from the document
2879 * tree, sans children, or undefined if the element was already not in the
2880 * document.
2881 */
2882 goog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement;
2883
2884
2885 /**
2886 * Returns an array containing just the element children of the given element.
2887 * @param {Element} element The element whose element children we want.
2888 * @return {!(Array<!Element>|NodeList<!Element>)} An array or array-like list
2889 * of just the element children of the given element.
2890 */
2891 goog.dom.DomHelper.prototype.getChildren = goog.dom.getChildren;
2892
2893
2894 /**
2895 * Returns the first child node that is an element.
2896 * @param {Node} node The node to get the first child element of.
2897 * @return {Element} The first child node of {@code node} that is an element.
2898 */
2899 goog.dom.DomHelper.prototype.getFirstElementChild =
2900 goog.dom.getFirstElementChild;
2901
2902
2903 /**
2904 * Returns the last child node that is an element.
2905 * @param {Node} node The node to get the last child element of.
2906 * @return {Element} The last child node of {@code node} that is an element.
2907 */
2908 goog.dom.DomHelper.prototype.getLastElementChild = goog.dom.getLastElementChild;
2909
2910
2911 /**
2912 * Returns the first next sibling that is an element.
2913 * @param {Node} node The node to get the next sibling element of.
2914 * @return {Element} The next sibling of {@code node} that is an element.
2915 */
2916 goog.dom.DomHelper.prototype.getNextElementSibling =
2917 goog.dom.getNextElementSibling;
2918
2919
2920 /**
2921 * Returns the first previous sibling that is an element.
2922 * @param {Node} node The node to get the previous sibling element of.
2923 * @return {Element} The first previous sibling of {@code node} that is
2924 * an element.
2925 */
2926 goog.dom.DomHelper.prototype.getPreviousElementSibling =
2927 goog.dom.getPreviousElementSibling;
2928
2929
2930 /**
2931 * Returns the next node in source order from the given node.
2932 * @param {Node} node The node.
2933 * @return {Node} The next node in the DOM tree, or null if this was the last
2934 * node.
2935 */
2936 goog.dom.DomHelper.prototype.getNextNode = goog.dom.getNextNode;
2937
2938
2939 /**
2940 * Returns the previous node in source order from the given node.
2941 * @param {Node} node The node.
2942 * @return {Node} The previous node in the DOM tree, or null if this was the
2943 * first node.
2944 */
2945 goog.dom.DomHelper.prototype.getPreviousNode = goog.dom.getPreviousNode;
2946
2947
2948 /**
2949 * Whether the object looks like a DOM node.
2950 * @param {?} obj The object being tested for node likeness.
2951 * @return {boolean} Whether the object looks like a DOM node.
2952 */
2953 goog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike;
2954
2955
2956 /**
2957 * Whether the object looks like an Element.
2958 * @param {?} obj The object being tested for Element likeness.
2959 * @return {boolean} Whether the object looks like an Element.
2960 */
2961 goog.dom.DomHelper.prototype.isElement = goog.dom.isElement;
2962
2963
2964 /**
2965 * Returns true if the specified value is a Window object. This includes the
2966 * global window for HTML pages, and iframe windows.
2967 * @param {?} obj Variable to test.
2968 * @return {boolean} Whether the variable is a window.
2969 */
2970 goog.dom.DomHelper.prototype.isWindow = goog.dom.isWindow;
2971
2972
2973 /**
2974 * Returns an element's parent, if it's an Element.
2975 * @param {Element} element The DOM element.
2976 * @return {Element} The parent, or null if not an Element.
2977 */
2978 goog.dom.DomHelper.prototype.getParentElement = goog.dom.getParentElement;
2979
2980
2981 /**
2982 * Whether a node contains another node.
2983 * @param {Node} parent The node that should contain the other node.
2984 * @param {Node} descendant The node to test presence of.
2985 * @return {boolean} Whether the parent node contains the descendent node.
2986 */
2987 goog.dom.DomHelper.prototype.contains = goog.dom.contains;
2988
2989
2990 /**
2991 * Compares the document order of two nodes, returning 0 if they are the same
2992 * node, a negative number if node1 is before node2, and a positive number if
2993 * node2 is before node1. Note that we compare the order the tags appear in the
2994 * document so in the tree <b><i>text</i></b> the B node is considered to be
2995 * before the I node.
2996 *
2997 * @param {Node} node1 The first node to compare.
2998 * @param {Node} node2 The second node to compare.
2999 * @return {number} 0 if the nodes are the same node, a negative number if node1
3000 * is before node2, and a positive number if node2 is before node1.
3001 */
3002 goog.dom.DomHelper.prototype.compareNodeOrder = goog.dom.compareNodeOrder;
3003
3004
3005 /**
3006 * Find the deepest common ancestor of the given nodes.
3007 * @param {...Node} var_args The nodes to find a common ancestor of.
3008 * @return {Node} The common ancestor of the nodes, or null if there is none.
3009 * null will only be returned if two or more of the nodes are from different
3010 * documents.
3011 */
3012 goog.dom.DomHelper.prototype.findCommonAncestor = goog.dom.findCommonAncestor;
3013
3014
3015 /**
3016 * Returns the owner document for a node.
3017 * @param {Node} node The node to get the document for.
3018 * @return {!Document} The document owning the node.
3019 */
3020 goog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument;
3021
3022
3023 /**
3024 * Cross browser function for getting the document element of an iframe.
3025 * @param {Element} iframe Iframe element.
3026 * @return {!Document} The frame content document.
3027 */
3028 goog.dom.DomHelper.prototype.getFrameContentDocument =
3029 goog.dom.getFrameContentDocument;
3030
3031
3032 /**
3033 * Cross browser function for getting the window of a frame or iframe.
3034 * @param {Element} frame Frame element.
3035 * @return {Window} The window associated with the given frame.
3036 */
3037 goog.dom.DomHelper.prototype.getFrameContentWindow =
3038 goog.dom.getFrameContentWindow;
3039
3040
3041 /**
3042 * Sets the text content of a node, with cross-browser support.
3043 * @param {Node} node The node to change the text content of.
3044 * @param {string|number} text The value that should replace the node's content.
3045 */
3046 goog.dom.DomHelper.prototype.setTextContent = goog.dom.setTextContent;
3047
3048
3049 /**
3050 * Gets the outerHTML of a node, which islike innerHTML, except that it
3051 * actually contains the HTML of the node itself.
3052 * @param {Element} element The element to get the HTML of.
3053 * @return {string} The outerHTML of the given element.
3054 */
3055 goog.dom.DomHelper.prototype.getOuterHtml = goog.dom.getOuterHtml;
3056
3057
3058 /**
3059 * Finds the first descendant node that matches the filter function. This does
3060 * a depth first search.
3061 * @param {Node} root The root of the tree to search.
3062 * @param {function(Node) : boolean} p The filter function.
3063 * @return {Node|undefined} The found node or undefined if none is found.
3064 */
3065 goog.dom.DomHelper.prototype.findNode = goog.dom.findNode;
3066
3067
3068 /**
3069 * Finds all the descendant nodes that matches the filter function. This does a
3070 * depth first search.
3071 * @param {Node} root The root of the tree to search.
3072 * @param {function(Node) : boolean} p The filter function.
3073 * @return {Array<Node>} The found nodes or an empty array if none are found.
3074 */
3075 goog.dom.DomHelper.prototype.findNodes = goog.dom.findNodes;
3076
3077
3078 /**
3079 * Returns true if the element has a tab index that allows it to receive
3080 * keyboard focus (tabIndex >= 0), false otherwise. Note that some elements
3081 * natively support keyboard focus, even if they have no tab index.
3082 * @param {!Element} element Element to check.
3083 * @return {boolean} Whether the element has a tab index that allows keyboard
3084 * focus.
3085 */
3086 goog.dom.DomHelper.prototype.isFocusableTabIndex = goog.dom.isFocusableTabIndex;
3087
3088
3089 /**
3090 * Enables or disables keyboard focus support on the element via its tab index.
3091 * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true
3092 * (or elements that natively support keyboard focus, like form elements) can
3093 * receive keyboard focus. See http://go/tabindex for more info.
3094 * @param {Element} element Element whose tab index is to be changed.
3095 * @param {boolean} enable Whether to set or remove a tab index on the element
3096 * that supports keyboard focus.
3097 */
3098 goog.dom.DomHelper.prototype.setFocusableTabIndex =
3099 goog.dom.setFocusableTabIndex;
3100
3101
3102 /**
3103 * Returns true if the element can be focused, i.e. it has a tab index that
3104 * allows it to receive keyboard focus (tabIndex >= 0), or it is an element
3105 * that natively supports keyboard focus.
3106 * @param {!Element} element Element to check.
3107 * @return {boolean} Whether the element allows keyboard focus.
3108 */
3109 goog.dom.DomHelper.prototype.isFocusable = goog.dom.isFocusable;
3110
3111
3112 /**
3113 * Returns the text contents of the current node, without markup. New lines are
3114 * stripped and whitespace is collapsed, such that each character would be
3115 * visible.
3116 *
3117 * In browsers that support it, innerText is used. Other browsers attempt to
3118 * simulate it via node traversal. Line breaks are canonicalized in IE.
3119 *
3120 * @param {Node} node The node from which we are getting content.
3121 * @return {string} The text content.
3122 */
3123 goog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent;
3124
3125
3126 /**
3127 * Returns the text length of the text contained in a node, without markup. This
3128 * is equivalent to the selection length if the node was selected, or the number
3129 * of cursor movements to traverse the node. Images & BRs take one space. New
3130 * lines are ignored.
3131 *
3132 * @param {Node} node The node whose text content length is being calculated.
3133 * @return {number} The length of {@code node}'s text content.
3134 */
3135 goog.dom.DomHelper.prototype.getNodeTextLength = goog.dom.getNodeTextLength;
3136
3137
3138 /**
3139 * Returns the text offset of a node relative to one of its ancestors. The text
3140 * length is the same as the length calculated by
3141 * {@code goog.dom.getNodeTextLength}.
3142 *
3143 * @param {Node} node The node whose offset is being calculated.
3144 * @param {Node=} opt_offsetParent Defaults to the node's owner document's body.
3145 * @return {number} The text offset.
3146 */
3147 goog.dom.DomHelper.prototype.getNodeTextOffset = goog.dom.getNodeTextOffset;
3148
3149
3150 /**
3151 * Returns the node at a given offset in a parent node. If an object is
3152 * provided for the optional third parameter, the node and the remainder of the
3153 * offset will stored as properties of this object.
3154 * @param {Node} parent The parent node.
3155 * @param {number} offset The offset into the parent node.
3156 * @param {Object=} opt_result Object to be used to store the return value. The
3157 * return value will be stored in the form {node: Node, remainder: number}
3158 * if this object is provided.
3159 * @return {Node} The node at the given offset.
3160 */
3161 goog.dom.DomHelper.prototype.getNodeAtOffset = goog.dom.getNodeAtOffset;
3162
3163
3164 /**
3165 * Returns true if the object is a {@code NodeList}. To qualify as a NodeList,
3166 * the object must have a numeric length property and an item function (which
3167 * has type 'string' on IE for some reason).
3168 * @param {Object} val Object to test.
3169 * @return {boolean} Whether the object is a NodeList.
3170 */
3171 goog.dom.DomHelper.prototype.isNodeList = goog.dom.isNodeList;
3172
3173
3174 /**
3175 * Walks up the DOM hierarchy returning the first ancestor that has the passed
3176 * tag name and/or class name. If the passed element matches the specified
3177 * criteria, the element itself is returned.
3178 * @param {Node} element The DOM node to start with.
3179 * @param {?(goog.dom.TagName<T>|string)=} opt_tag The tag name to match (or
3180 * null/undefined to match only based on class name).
3181 * @param {?string=} opt_class The class name to match (or null/undefined to
3182 * match only based on tag name).
3183 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
3184 * dom.
3185 * @return {?R} The first ancestor that matches the passed criteria, or
3186 * null if no match is found. The return type is {?Element} if opt_tag is
3187 * not a member of goog.dom.TagName or a more specific type if it is (e.g.
3188 * {?HTMLAnchorElement} for goog.dom.TagName.A).
3189 * @template T
3190 * @template R := cond(isUnknown(T), 'Element', T) =:
3191 */
3192 goog.dom.DomHelper.prototype.getAncestorByTagNameAndClass =
3193 goog.dom.getAncestorByTagNameAndClass;
3194
3195
3196 /**
3197 * Walks up the DOM hierarchy returning the first ancestor that has the passed
3198 * class name. If the passed element matches the specified criteria, the
3199 * element itself is returned.
3200 * @param {Node} element The DOM node to start with.
3201 * @param {string} class The class name to match.
3202 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
3203 * dom.
3204 * @return {Element} The first ancestor that matches the passed criteria, or
3205 * null if none match.
3206 */
3207 goog.dom.DomHelper.prototype.getAncestorByClass = goog.dom.getAncestorByClass;
3208
3209
3210 /**
3211 * Walks up the DOM hierarchy returning the first ancestor that passes the
3212 * matcher function.
3213 * @param {Node} element The DOM node to start with.
3214 * @param {function(Node) : boolean} matcher A function that returns true if the
3215 * passed node matches the desired criteria.
3216 * @param {boolean=} opt_includeNode If true, the node itself is included in
3217 * the search (the first call to the matcher will pass startElement as
3218 * the node to test).
3219 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
3220 * dom.
3221 * @return {Node} DOM node that matched the matcher, or null if there was
3222 * no match.
3223 */
3224 goog.dom.DomHelper.prototype.getAncestor = goog.dom.getAncestor;
3225
3226
3227 /**
3228 * Gets '2d' context of a canvas. Shortcut for canvas.getContext('2d') with a
3229 * type information.
3230 * @param {!HTMLCanvasElement} canvas
3231 * @return {!CanvasRenderingContext2D}
3232 */
3233 goog.dom.DomHelper.prototype.getCanvasContext2D = goog.dom.getCanvasContext2D;