lib/goog/dom/dom.js

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