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 (key in goog.dom.DIRECT_ATTRIBUTE_MAP_) {
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 = 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,i
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: http://msdn.microsoft.com/workshop/author/
709 // dhtml/reference/properties/name_2.asp
710 // Also does not allow setting of 'type' attribute on 'input' or 'button'.
711 if (!goog.dom.BrowserFeature.CAN_ADD_NAME_OR_TYPE_ATTRIBUTES && attributes &&
712 (attributes.name || attributes.type)) {
713 var tagNameArr = ['<', tagName];
714 if (attributes.name) {
715 tagNameArr.push(' name="', goog.string.htmlEscape(attributes.name),
716 '"');
717 }
718 if (attributes.type) {
719 tagNameArr.push(' type="', goog.string.htmlEscape(attributes.type),
720 '"');
721
722 // Clone attributes map to remove 'type' without mutating the input.
723 var clone = {};
724 goog.object.extend(clone, attributes);
725
726 // JSCompiler can't see how goog.object.extend added this property,
727 // because it was essentially added by reflection.
728 // So it needs to be quoted.
729 delete clone['type'];
730
731 attributes = clone;
732 }
733 tagNameArr.push('>');
734 tagName = tagNameArr.join('');
735 }
736
737 var element = doc.createElement(tagName);
738
739 if (attributes) {
740 if (goog.isString(attributes)) {
741 element.className = attributes;
742 } else if (goog.isArray(attributes)) {
743 element.className = attributes.join(' ');
744 } else {
745 goog.dom.setProperties(element, attributes);
746 }
747 }
748
749 if (args.length > 2) {
750 goog.dom.append_(doc, element, args, 2);
751 }
752
753 return element;
754};
755
756
757/**
758 * Appends a node with text or other nodes.
759 * @param {!Document} doc The document to create new nodes in.
760 * @param {!Node} parent The node to append nodes to.
761 * @param {!Arguments} args The values to add. See {@code goog.dom.append}.
762 * @param {number} startIndex The index of the array to start from.
763 * @private
764 */
765goog.dom.append_ = function(doc, parent, args, startIndex) {
766 function childHandler(child) {
767 // TODO(user): More coercion, ala MochiKit?
768 if (child) {
769 parent.appendChild(goog.isString(child) ?
770 doc.createTextNode(child) : child);
771 }
772 }
773
774 for (var i = startIndex; i < args.length; i++) {
775 var arg = args[i];
776 // TODO(attila): Fix isArrayLike to return false for a text node.
777 if (goog.isArrayLike(arg) && !goog.dom.isNodeLike(arg)) {
778 // If the argument is a node list, not a real array, use a clone,
779 // because forEach can't be used to mutate a NodeList.
780 goog.array.forEach(goog.dom.isNodeList(arg) ?
781 goog.array.toArray(arg) : arg,
782 childHandler);
783 } else {
784 childHandler(arg);
785 }
786 }
787};
788
789
790/**
791 * Alias for {@code createDom}.
792 * @param {string} tagName Tag to create.
793 * @param {(string|Object)=} opt_attributes If object, then a map of name-value
794 * pairs for attributes. If a string, then this is the className of the new
795 * element.
796 * @param {...(Object|string|Array|NodeList)} var_args Further DOM nodes or
797 * strings for text nodes. If one of the var_args is an array, its
798 * children will be added as childNodes instead.
799 * @return {!Element} Reference to a DOM node.
800 * @deprecated Use {@link goog.dom.createDom} instead.
801 */
802goog.dom.$dom = goog.dom.createDom;
803
804
805/**
806 * Creates a new element.
807 * @param {string} name Tag name.
808 * @return {!Element} The new element.
809 */
810goog.dom.createElement = function(name) {
811 return document.createElement(name);
812};
813
814
815/**
816 * Creates a new text node.
817 * @param {number|string} content Content.
818 * @return {!Text} The new text node.
819 */
820goog.dom.createTextNode = function(content) {
821 return document.createTextNode(String(content));
822};
823
824
825/**
826 * Create a table.
827 * @param {number} rows The number of rows in the table. Must be >= 1.
828 * @param {number} columns The number of columns in the table. Must be >= 1.
829 * @param {boolean=} opt_fillWithNbsp If true, fills table entries with
830 * {@code goog.string.Unicode.NBSP} characters.
831 * @return {!Element} The created table.
832 */
833goog.dom.createTable = function(rows, columns, opt_fillWithNbsp) {
834 // TODO(user): Return HTMLTableElement, also in prototype function.
835 // Callers need to be updated to e.g. not assign numbers to table.cellSpacing.
836 return goog.dom.createTable_(document, rows, columns, !!opt_fillWithNbsp);
837};
838
839
840/**
841 * Create a table.
842 * @param {!Document} doc Document object to use to create the table.
843 * @param {number} rows The number of rows in the table. Must be >= 1.
844 * @param {number} columns The number of columns in the table. Must be >= 1.
845 * @param {boolean} fillWithNbsp If true, fills table entries with
846 * {@code goog.string.Unicode.NBSP} characters.
847 * @return {!HTMLTableElement} The created table.
848 * @private
849 */
850goog.dom.createTable_ = function(doc, rows, columns, fillWithNbsp) {
851 var table = /** @type {!HTMLTableElement} */
852 (doc.createElement(goog.dom.TagName.TABLE));
853 var tbody = table.appendChild(doc.createElement(goog.dom.TagName.TBODY));
854 for (var i = 0; i < rows; i++) {
855 var tr = doc.createElement(goog.dom.TagName.TR);
856 for (var j = 0; j < columns; j++) {
857 var td = doc.createElement(goog.dom.TagName.TD);
858 // IE <= 9 will create a text node if we set text content to the empty
859 // string, so we avoid doing it unless necessary. This ensures that the
860 // same DOM tree is returned on all browsers.
861 if (fillWithNbsp) {
862 goog.dom.setTextContent(td, goog.string.Unicode.NBSP);
863 }
864 tr.appendChild(td);
865 }
866 tbody.appendChild(tr);
867 }
868 return table;
869};
870
871
872/**
873 * Converts HTML markup into a node.
874 * @param {!goog.html.SafeHtml} html The HTML markup to convert.
875 * @return {!Node} The resulting node.
876 */
877goog.dom.safeHtmlToNode = function(html) {
878 return goog.dom.safeHtmlToNode_(document, html);
879};
880
881
882/**
883 * Helper for {@code safeHtmlToNode}.
884 * @param {!Document} doc The document.
885 * @param {!goog.html.SafeHtml} html The HTML markup to convert.
886 * @return {!Node} The resulting node.
887 * @private
888 */
889goog.dom.safeHtmlToNode_ = function(doc, html) {
890 var tempDiv = doc.createElement(goog.dom.TagName.DIV);
891 if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) {
892 goog.dom.safe.setInnerHtml(tempDiv,
893 goog.html.SafeHtml.concat(goog.html.SafeHtml.create('br'), html));
894 tempDiv.removeChild(tempDiv.firstChild);
895 } else {
896 goog.dom.safe.setInnerHtml(tempDiv, html);
897 }
898 return goog.dom.childrenToNode_(doc, tempDiv);
899};
900
901
902/**
903 * Converts an HTML string into a document fragment. The string must be
904 * sanitized in order to avoid cross-site scripting. For example
905 * {@code goog.dom.htmlToDocumentFragment('&lt;img src=x onerror=alert(0)&gt;')}
906 * triggers an alert in all browsers, even if the returned document fragment
907 * is thrown away immediately.
908 *
909 * @param {string} htmlString The HTML string to convert.
910 * @return {!Node} The resulting document fragment.
911 */
912goog.dom.htmlToDocumentFragment = function(htmlString) {
913 return goog.dom.htmlToDocumentFragment_(document, htmlString);
914};
915
916
917// TODO(jakubvrana): Merge with {@code safeHtmlToNode_}.
918/**
919 * Helper for {@code htmlToDocumentFragment}.
920 *
921 * @param {!Document} doc The document.
922 * @param {string} htmlString The HTML string to convert.
923 * @return {!Node} The resulting document fragment.
924 * @private
925 */
926goog.dom.htmlToDocumentFragment_ = function(doc, htmlString) {
927 var tempDiv = doc.createElement(goog.dom.TagName.DIV);
928 if (goog.dom.BrowserFeature.INNER_HTML_NEEDS_SCOPED_ELEMENT) {
929 tempDiv.innerHTML = '<br>' + htmlString;
930 tempDiv.removeChild(tempDiv.firstChild);
931 } else {
932 tempDiv.innerHTML = htmlString;
933 }
934 return goog.dom.childrenToNode_(doc, tempDiv);
935};
936
937
938/**
939 * Helper for {@code htmlToDocumentFragment_}.
940 * @param {!Document} doc The document.
941 * @param {!Node} tempDiv The input node.
942 * @return {!Node} The resulting node.
943 * @private
944 */
945goog.dom.childrenToNode_ = function(doc, tempDiv) {
946 if (tempDiv.childNodes.length == 1) {
947 return tempDiv.removeChild(tempDiv.firstChild);
948 } else {
949 var fragment = doc.createDocumentFragment();
950 while (tempDiv.firstChild) {
951 fragment.appendChild(tempDiv.firstChild);
952 }
953 return fragment;
954 }
955};
956
957
958/**
959 * Returns true if the browser is in "CSS1-compatible" (standards-compliant)
960 * mode, false otherwise.
961 * @return {boolean} True if in CSS1-compatible mode.
962 */
963goog.dom.isCss1CompatMode = function() {
964 return goog.dom.isCss1CompatMode_(document);
965};
966
967
968/**
969 * Returns true if the browser is in "CSS1-compatible" (standards-compliant)
970 * mode, false otherwise.
971 * @param {!Document} doc The document to check.
972 * @return {boolean} True if in CSS1-compatible mode.
973 * @private
974 */
975goog.dom.isCss1CompatMode_ = function(doc) {
976 if (goog.dom.COMPAT_MODE_KNOWN_) {
977 return goog.dom.ASSUME_STANDARDS_MODE;
978 }
979
980 return doc.compatMode == 'CSS1Compat';
981};
982
983
984/**
985 * Determines if the given node can contain children, intended to be used for
986 * HTML generation.
987 *
988 * IE natively supports node.canHaveChildren but has inconsistent behavior.
989 * Prior to IE8 the base tag allows children and in IE9 all nodes return true
990 * for canHaveChildren.
991 *
992 * In practice all non-IE browsers allow you to add children to any node, but
993 * the behavior is inconsistent:
994 *
995 * <pre>
996 * var a = document.createElement(goog.dom.TagName.BR);
997 * a.appendChild(document.createTextNode('foo'));
998 * a.appendChild(document.createTextNode('bar'));
999 * console.log(a.childNodes.length); // 2
1000 * console.log(a.innerHTML); // Chrome: "", IE9: "foobar", FF3.5: "foobar"
1001 * </pre>
1002 *
1003 * For more information, see:
1004 * http://dev.w3.org/html5/markup/syntax.html#syntax-elements
1005 *
1006 * TODO(user): Rename shouldAllowChildren() ?
1007 *
1008 * @param {Node} node The node to check.
1009 * @return {boolean} Whether the node can contain children.
1010 */
1011goog.dom.canHaveChildren = function(node) {
1012 if (node.nodeType != goog.dom.NodeType.ELEMENT) {
1013 return false;
1014 }
1015 switch (node.tagName) {
1016 case goog.dom.TagName.APPLET:
1017 case goog.dom.TagName.AREA:
1018 case goog.dom.TagName.BASE:
1019 case goog.dom.TagName.BR:
1020 case goog.dom.TagName.COL:
1021 case goog.dom.TagName.COMMAND:
1022 case goog.dom.TagName.EMBED:
1023 case goog.dom.TagName.FRAME:
1024 case goog.dom.TagName.HR:
1025 case goog.dom.TagName.IMG:
1026 case goog.dom.TagName.INPUT:
1027 case goog.dom.TagName.IFRAME:
1028 case goog.dom.TagName.ISINDEX:
1029 case goog.dom.TagName.KEYGEN:
1030 case goog.dom.TagName.LINK:
1031 case goog.dom.TagName.NOFRAMES:
1032 case goog.dom.TagName.NOSCRIPT:
1033 case goog.dom.TagName.META:
1034 case goog.dom.TagName.OBJECT:
1035 case goog.dom.TagName.PARAM:
1036 case goog.dom.TagName.SCRIPT:
1037 case goog.dom.TagName.SOURCE:
1038 case goog.dom.TagName.STYLE:
1039 case goog.dom.TagName.TRACK:
1040 case goog.dom.TagName.WBR:
1041 return false;
1042 }
1043 return true;
1044};
1045
1046
1047/**
1048 * Appends a child to a node.
1049 * @param {Node} parent Parent.
1050 * @param {Node} child Child.
1051 */
1052goog.dom.appendChild = function(parent, child) {
1053 parent.appendChild(child);
1054};
1055
1056
1057/**
1058 * Appends a node with text or other nodes.
1059 * @param {!Node} parent The node to append nodes to.
1060 * @param {...goog.dom.Appendable} var_args The things to append to the node.
1061 * If this is a Node it is appended as is.
1062 * If this is a string then a text node is appended.
1063 * If this is an array like object then fields 0 to length - 1 are appended.
1064 */
1065goog.dom.append = function(parent, var_args) {
1066 goog.dom.append_(goog.dom.getOwnerDocument(parent), parent, arguments, 1);
1067};
1068
1069
1070/**
1071 * Removes all the child nodes on a DOM node.
1072 * @param {Node} node Node to remove children from.
1073 */
1074goog.dom.removeChildren = function(node) {
1075 // Note: Iterations over live collections can be slow, this is the fastest
1076 // we could find. The double parenthesis are used to prevent JsCompiler and
1077 // strict warnings.
1078 var child;
1079 while ((child = node.firstChild)) {
1080 node.removeChild(child);
1081 }
1082};
1083
1084
1085/**
1086 * Inserts a new node before an existing reference node (i.e. as the previous
1087 * sibling). If the reference node has no parent, then does nothing.
1088 * @param {Node} newNode Node to insert.
1089 * @param {Node} refNode Reference node to insert before.
1090 */
1091goog.dom.insertSiblingBefore = function(newNode, refNode) {
1092 if (refNode.parentNode) {
1093 refNode.parentNode.insertBefore(newNode, refNode);
1094 }
1095};
1096
1097
1098/**
1099 * Inserts a new node after an existing reference node (i.e. as the next
1100 * sibling). If the reference node has no parent, then does nothing.
1101 * @param {Node} newNode Node to insert.
1102 * @param {Node} refNode Reference node to insert after.
1103 */
1104goog.dom.insertSiblingAfter = function(newNode, refNode) {
1105 if (refNode.parentNode) {
1106 refNode.parentNode.insertBefore(newNode, refNode.nextSibling);
1107 }
1108};
1109
1110
1111/**
1112 * Insert a child at a given index. If index is larger than the number of child
1113 * nodes that the parent currently has, the node is inserted as the last child
1114 * node.
1115 * @param {Element} parent The element into which to insert the child.
1116 * @param {Node} child The element to insert.
1117 * @param {number} index The index at which to insert the new child node. Must
1118 * not be negative.
1119 */
1120goog.dom.insertChildAt = function(parent, child, index) {
1121 // Note that if the second argument is null, insertBefore
1122 // will append the child at the end of the list of children.
1123 parent.insertBefore(child, parent.childNodes[index] || null);
1124};
1125
1126
1127/**
1128 * Removes a node from its parent.
1129 * @param {Node} node The node to remove.
1130 * @return {Node} The node removed if removed; else, null.
1131 */
1132goog.dom.removeNode = function(node) {
1133 return node && node.parentNode ? node.parentNode.removeChild(node) : null;
1134};
1135
1136
1137/**
1138 * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no
1139 * parent.
1140 * @param {Node} newNode Node to insert.
1141 * @param {Node} oldNode Node to replace.
1142 */
1143goog.dom.replaceNode = function(newNode, oldNode) {
1144 var parent = oldNode.parentNode;
1145 if (parent) {
1146 parent.replaceChild(newNode, oldNode);
1147 }
1148};
1149
1150
1151/**
1152 * Flattens an element. That is, removes it and replace it with its children.
1153 * Does nothing if the element is not in the document.
1154 * @param {Element} element The element to flatten.
1155 * @return {Element|undefined} The original element, detached from the document
1156 * tree, sans children; or undefined, if the element was not in the document
1157 * to begin with.
1158 */
1159goog.dom.flattenElement = function(element) {
1160 var child, parent = element.parentNode;
1161 if (parent && parent.nodeType != goog.dom.NodeType.DOCUMENT_FRAGMENT) {
1162 // Use IE DOM method (supported by Opera too) if available
1163 if (element.removeNode) {
1164 return /** @type {Element} */ (element.removeNode(false));
1165 } else {
1166 // Move all children of the original node up one level.
1167 while ((child = element.firstChild)) {
1168 parent.insertBefore(child, element);
1169 }
1170
1171 // Detach the original element.
1172 return /** @type {Element} */ (goog.dom.removeNode(element));
1173 }
1174 }
1175};
1176
1177
1178/**
1179 * Returns an array containing just the element children of the given element.
1180 * @param {Element} element The element whose element children we want.
1181 * @return {!(Array|NodeList)} An array or array-like list of just the element
1182 * children of the given element.
1183 */
1184goog.dom.getChildren = function(element) {
1185 // We check if the children attribute is supported for child elements
1186 // since IE8 misuses the attribute by also including comments.
1187 if (goog.dom.BrowserFeature.CAN_USE_CHILDREN_ATTRIBUTE &&
1188 element.children != undefined) {
1189 return element.children;
1190 }
1191 // Fall back to manually filtering the element's child nodes.
1192 return goog.array.filter(element.childNodes, function(node) {
1193 return node.nodeType == goog.dom.NodeType.ELEMENT;
1194 });
1195};
1196
1197
1198/**
1199 * Returns the first child node that is an element.
1200 * @param {Node} node The node to get the first child element of.
1201 * @return {Element} The first child node of {@code node} that is an element.
1202 */
1203goog.dom.getFirstElementChild = function(node) {
1204 if (node.firstElementChild != undefined) {
1205 return /** @type {!Element} */(node).firstElementChild;
1206 }
1207 return goog.dom.getNextElementNode_(node.firstChild, true);
1208};
1209
1210
1211/**
1212 * Returns the last child node that is an element.
1213 * @param {Node} node The node to get the last child element of.
1214 * @return {Element} The last child node of {@code node} that is an element.
1215 */
1216goog.dom.getLastElementChild = function(node) {
1217 if (node.lastElementChild != undefined) {
1218 return /** @type {!Element} */(node).lastElementChild;
1219 }
1220 return goog.dom.getNextElementNode_(node.lastChild, false);
1221};
1222
1223
1224/**
1225 * Returns the first next sibling that is an element.
1226 * @param {Node} node The node to get the next sibling element of.
1227 * @return {Element} The next sibling of {@code node} that is an element.
1228 */
1229goog.dom.getNextElementSibling = function(node) {
1230 if (node.nextElementSibling != undefined) {
1231 return /** @type {!Element} */(node).nextElementSibling;
1232 }
1233 return goog.dom.getNextElementNode_(node.nextSibling, true);
1234};
1235
1236
1237/**
1238 * Returns the first previous sibling that is an element.
1239 * @param {Node} node The node to get the previous sibling element of.
1240 * @return {Element} The first previous sibling of {@code node} that is
1241 * an element.
1242 */
1243goog.dom.getPreviousElementSibling = function(node) {
1244 if (node.previousElementSibling != undefined) {
1245 return /** @type {!Element} */(node).previousElementSibling;
1246 }
1247 return goog.dom.getNextElementNode_(node.previousSibling, false);
1248};
1249
1250
1251/**
1252 * Returns the first node that is an element in the specified direction,
1253 * starting with {@code node}.
1254 * @param {Node} node The node to get the next element from.
1255 * @param {boolean} forward Whether to look forwards or backwards.
1256 * @return {Element} The first element.
1257 * @private
1258 */
1259goog.dom.getNextElementNode_ = function(node, forward) {
1260 while (node && node.nodeType != goog.dom.NodeType.ELEMENT) {
1261 node = forward ? node.nextSibling : node.previousSibling;
1262 }
1263
1264 return /** @type {Element} */ (node);
1265};
1266
1267
1268/**
1269 * Returns the next node in source order from the given node.
1270 * @param {Node} node The node.
1271 * @return {Node} The next node in the DOM tree, or null if this was the last
1272 * node.
1273 */
1274goog.dom.getNextNode = function(node) {
1275 if (!node) {
1276 return null;
1277 }
1278
1279 if (node.firstChild) {
1280 return node.firstChild;
1281 }
1282
1283 while (node && !node.nextSibling) {
1284 node = node.parentNode;
1285 }
1286
1287 return node ? node.nextSibling : null;
1288};
1289
1290
1291/**
1292 * Returns the previous node in source order from the given node.
1293 * @param {Node} node The node.
1294 * @return {Node} The previous node in the DOM tree, or null if this was the
1295 * first node.
1296 */
1297goog.dom.getPreviousNode = function(node) {
1298 if (!node) {
1299 return null;
1300 }
1301
1302 if (!node.previousSibling) {
1303 return node.parentNode;
1304 }
1305
1306 node = node.previousSibling;
1307 while (node && node.lastChild) {
1308 node = node.lastChild;
1309 }
1310
1311 return node;
1312};
1313
1314
1315/**
1316 * Whether the object looks like a DOM node.
1317 * @param {?} obj The object being tested for node likeness.
1318 * @return {boolean} Whether the object looks like a DOM node.
1319 */
1320goog.dom.isNodeLike = function(obj) {
1321 return goog.isObject(obj) && obj.nodeType > 0;
1322};
1323
1324
1325/**
1326 * Whether the object looks like an Element.
1327 * @param {?} obj The object being tested for Element likeness.
1328 * @return {boolean} Whether the object looks like an Element.
1329 */
1330goog.dom.isElement = function(obj) {
1331 return goog.isObject(obj) && obj.nodeType == goog.dom.NodeType.ELEMENT;
1332};
1333
1334
1335/**
1336 * Returns true if the specified value is a Window object. This includes the
1337 * global window for HTML pages, and iframe windows.
1338 * @param {?} obj Variable to test.
1339 * @return {boolean} Whether the variable is a window.
1340 */
1341goog.dom.isWindow = function(obj) {
1342 return goog.isObject(obj) && obj['window'] == obj;
1343};
1344
1345
1346/**
1347 * Returns an element's parent, if it's an Element.
1348 * @param {Element} element The DOM element.
1349 * @return {Element} The parent, or null if not an Element.
1350 */
1351goog.dom.getParentElement = function(element) {
1352 var parent;
1353 if (goog.dom.BrowserFeature.CAN_USE_PARENT_ELEMENT_PROPERTY) {
1354 var isIe9 = goog.userAgent.IE &&
1355 goog.userAgent.isVersionOrHigher('9') &&
1356 !goog.userAgent.isVersionOrHigher('10');
1357 // SVG elements in IE9 can't use the parentElement property.
1358 // goog.global['SVGElement'] is not defined in IE9 quirks mode.
1359 if (!(isIe9 && goog.global['SVGElement'] &&
1360 element instanceof goog.global['SVGElement'])) {
1361 parent = element.parentElement;
1362 if (parent) {
1363 return parent;
1364 }
1365 }
1366 }
1367 parent = element.parentNode;
1368 return goog.dom.isElement(parent) ? /** @type {!Element} */ (parent) : null;
1369};
1370
1371
1372/**
1373 * Whether a node contains another node.
1374 * @param {Node} parent The node that should contain the other node.
1375 * @param {Node} descendant The node to test presence of.
1376 * @return {boolean} Whether the parent node contains the descendent node.
1377 */
1378goog.dom.contains = function(parent, descendant) {
1379 // We use browser specific methods for this if available since it is faster
1380 // that way.
1381
1382 // IE DOM
1383 if (parent.contains && descendant.nodeType == goog.dom.NodeType.ELEMENT) {
1384 return parent == descendant || parent.contains(descendant);
1385 }
1386
1387 // W3C DOM Level 3
1388 if (typeof parent.compareDocumentPosition != 'undefined') {
1389 return parent == descendant ||
1390 Boolean(parent.compareDocumentPosition(descendant) & 16);
1391 }
1392
1393 // W3C DOM Level 1
1394 while (descendant && parent != descendant) {
1395 descendant = descendant.parentNode;
1396 }
1397 return descendant == parent;
1398};
1399
1400
1401/**
1402 * Compares the document order of two nodes, returning 0 if they are the same
1403 * node, a negative number if node1 is before node2, and a positive number if
1404 * node2 is before node1. Note that we compare the order the tags appear in the
1405 * document so in the tree <b><i>text</i></b> the B node is considered to be
1406 * before the I node.
1407 *
1408 * @param {Node} node1 The first node to compare.
1409 * @param {Node} node2 The second node to compare.
1410 * @return {number} 0 if the nodes are the same node, a negative number if node1
1411 * is before node2, and a positive number if node2 is before node1.
1412 */
1413goog.dom.compareNodeOrder = function(node1, node2) {
1414 // Fall out quickly for equality.
1415 if (node1 == node2) {
1416 return 0;
1417 }
1418
1419 // Use compareDocumentPosition where available
1420 if (node1.compareDocumentPosition) {
1421 // 4 is the bitmask for FOLLOWS.
1422 return node1.compareDocumentPosition(node2) & 2 ? 1 : -1;
1423 }
1424
1425 // Special case for document nodes on IE 7 and 8.
1426 if (goog.userAgent.IE && !goog.userAgent.isDocumentModeOrHigher(9)) {
1427 if (node1.nodeType == goog.dom.NodeType.DOCUMENT) {
1428 return -1;
1429 }
1430 if (node2.nodeType == goog.dom.NodeType.DOCUMENT) {
1431 return 1;
1432 }
1433 }
1434
1435 // Process in IE using sourceIndex - we check to see if the first node has
1436 // a source index or if its parent has one.
1437 if ('sourceIndex' in node1 ||
1438 (node1.parentNode && 'sourceIndex' in node1.parentNode)) {
1439 var isElement1 = node1.nodeType == goog.dom.NodeType.ELEMENT;
1440 var isElement2 = node2.nodeType == goog.dom.NodeType.ELEMENT;
1441
1442 if (isElement1 && isElement2) {
1443 return node1.sourceIndex - node2.sourceIndex;
1444 } else {
1445 var parent1 = node1.parentNode;
1446 var parent2 = node2.parentNode;
1447
1448 if (parent1 == parent2) {
1449 return goog.dom.compareSiblingOrder_(node1, node2);
1450 }
1451
1452 if (!isElement1 && goog.dom.contains(parent1, node2)) {
1453 return -1 * goog.dom.compareParentsDescendantNodeIe_(node1, node2);
1454 }
1455
1456
1457 if (!isElement2 && goog.dom.contains(parent2, node1)) {
1458 return goog.dom.compareParentsDescendantNodeIe_(node2, node1);
1459 }
1460
1461 return (isElement1 ? node1.sourceIndex : parent1.sourceIndex) -
1462 (isElement2 ? node2.sourceIndex : parent2.sourceIndex);
1463 }
1464 }
1465
1466 // For Safari, we compare ranges.
1467 var doc = goog.dom.getOwnerDocument(node1);
1468
1469 var range1, range2;
1470 range1 = doc.createRange();
1471 range1.selectNode(node1);
1472 range1.collapse(true);
1473
1474 range2 = doc.createRange();
1475 range2.selectNode(node2);
1476 range2.collapse(true);
1477
1478 return range1.compareBoundaryPoints(goog.global['Range'].START_TO_END,
1479 range2);
1480};
1481
1482
1483/**
1484 * Utility function to compare the position of two nodes, when
1485 * {@code textNode}'s parent is an ancestor of {@code node}. If this entry
1486 * condition is not met, this function will attempt to reference a null object.
1487 * @param {!Node} textNode The textNode to compare.
1488 * @param {Node} node The node to compare.
1489 * @return {number} -1 if node is before textNode, +1 otherwise.
1490 * @private
1491 */
1492goog.dom.compareParentsDescendantNodeIe_ = function(textNode, node) {
1493 var parent = textNode.parentNode;
1494 if (parent == node) {
1495 // If textNode is a child of node, then node comes first.
1496 return -1;
1497 }
1498 var sibling = node;
1499 while (sibling.parentNode != parent) {
1500 sibling = sibling.parentNode;
1501 }
1502 return goog.dom.compareSiblingOrder_(sibling, textNode);
1503};
1504
1505
1506/**
1507 * Utility function to compare the position of two nodes known to be non-equal
1508 * siblings.
1509 * @param {Node} node1 The first node to compare.
1510 * @param {!Node} node2 The second node to compare.
1511 * @return {number} -1 if node1 is before node2, +1 otherwise.
1512 * @private
1513 */
1514goog.dom.compareSiblingOrder_ = function(node1, node2) {
1515 var s = node2;
1516 while ((s = s.previousSibling)) {
1517 if (s == node1) {
1518 // We just found node1 before node2.
1519 return -1;
1520 }
1521 }
1522
1523 // Since we didn't find it, node1 must be after node2.
1524 return 1;
1525};
1526
1527
1528/**
1529 * Find the deepest common ancestor of the given nodes.
1530 * @param {...Node} var_args The nodes to find a common ancestor of.
1531 * @return {Node} The common ancestor of the nodes, or null if there is none.
1532 * null will only be returned if two or more of the nodes are from different
1533 * documents.
1534 */
1535goog.dom.findCommonAncestor = function(var_args) {
1536 var i, count = arguments.length;
1537 if (!count) {
1538 return null;
1539 } else if (count == 1) {
1540 return arguments[0];
1541 }
1542
1543 var paths = [];
1544 var minLength = Infinity;
1545 for (i = 0; i < count; i++) {
1546 // Compute the list of ancestors.
1547 var ancestors = [];
1548 var node = arguments[i];
1549 while (node) {
1550 ancestors.unshift(node);
1551 node = node.parentNode;
1552 }
1553
1554 // Save the list for comparison.
1555 paths.push(ancestors);
1556 minLength = Math.min(minLength, ancestors.length);
1557 }
1558 var output = null;
1559 for (i = 0; i < minLength; i++) {
1560 var first = paths[0][i];
1561 for (var j = 1; j < count; j++) {
1562 if (first != paths[j][i]) {
1563 return output;
1564 }
1565 }
1566 output = first;
1567 }
1568 return output;
1569};
1570
1571
1572/**
1573 * Returns the owner document for a node.
1574 * @param {Node|Window} node The node to get the document for.
1575 * @return {!Document} The document owning the node.
1576 */
1577goog.dom.getOwnerDocument = function(node) {
1578 // TODO(nnaze): Update param signature to be non-nullable.
1579 goog.asserts.assert(node, 'Node cannot be null or undefined.');
1580 return /** @type {!Document} */ (
1581 node.nodeType == goog.dom.NodeType.DOCUMENT ? node :
1582 node.ownerDocument || node.document);
1583};
1584
1585
1586/**
1587 * Cross-browser function for getting the document element of a frame or iframe.
1588 * @param {Element} frame Frame element.
1589 * @return {!Document} The frame content document.
1590 */
1591goog.dom.getFrameContentDocument = function(frame) {
1592 var doc = frame.contentDocument || frame.contentWindow.document;
1593 return doc;
1594};
1595
1596
1597/**
1598 * Cross-browser function for getting the window of a frame or iframe.
1599 * @param {Element} frame Frame element.
1600 * @return {Window} The window associated with the given frame.
1601 */
1602goog.dom.getFrameContentWindow = function(frame) {
1603 return frame.contentWindow ||
1604 goog.dom.getWindow(goog.dom.getFrameContentDocument(frame));
1605};
1606
1607
1608/**
1609 * Sets the text content of a node, with cross-browser support.
1610 * @param {Node} node The node to change the text content of.
1611 * @param {string|number} text The value that should replace the node's content.
1612 */
1613goog.dom.setTextContent = function(node, text) {
1614 goog.asserts.assert(node != null,
1615 'goog.dom.setTextContent expects a non-null value for node');
1616
1617 if ('textContent' in node) {
1618 node.textContent = text;
1619 } else if (node.nodeType == goog.dom.NodeType.TEXT) {
1620 node.data = text;
1621 } else if (node.firstChild &&
1622 node.firstChild.nodeType == goog.dom.NodeType.TEXT) {
1623 // If the first child is a text node we just change its data and remove the
1624 // rest of the children.
1625 while (node.lastChild != node.firstChild) {
1626 node.removeChild(node.lastChild);
1627 }
1628 node.firstChild.data = text;
1629 } else {
1630 goog.dom.removeChildren(node);
1631 var doc = goog.dom.getOwnerDocument(node);
1632 node.appendChild(doc.createTextNode(String(text)));
1633 }
1634};
1635
1636
1637/**
1638 * Gets the outerHTML of a node, which islike innerHTML, except that it
1639 * actually contains the HTML of the node itself.
1640 * @param {Element} element The element to get the HTML of.
1641 * @return {string} The outerHTML of the given element.
1642 */
1643goog.dom.getOuterHtml = function(element) {
1644 // IE, Opera and WebKit all have outerHTML.
1645 if ('outerHTML' in element) {
1646 return element.outerHTML;
1647 } else {
1648 var doc = goog.dom.getOwnerDocument(element);
1649 var div = doc.createElement(goog.dom.TagName.DIV);
1650 div.appendChild(element.cloneNode(true));
1651 return div.innerHTML;
1652 }
1653};
1654
1655
1656/**
1657 * Finds the first descendant node that matches the filter function, using
1658 * a depth first search. This function offers the most general purpose way
1659 * of finding a matching element. You may also wish to consider
1660 * {@code goog.dom.query} which can express many matching criteria using
1661 * CSS selector expressions. These expressions often result in a more
1662 * compact representation of the desired result.
1663 * @see goog.dom.query
1664 *
1665 * @param {Node} root The root of the tree to search.
1666 * @param {function(Node) : boolean} p The filter function.
1667 * @return {Node|undefined} The found node or undefined if none is found.
1668 */
1669goog.dom.findNode = function(root, p) {
1670 var rv = [];
1671 var found = goog.dom.findNodes_(root, p, rv, true);
1672 return found ? rv[0] : undefined;
1673};
1674
1675
1676/**
1677 * Finds all the descendant nodes that match the filter function, using a
1678 * a depth first search. This function offers the most general-purpose way
1679 * of finding a set of matching elements. You may also wish to consider
1680 * {@code goog.dom.query} which can express many matching criteria using
1681 * CSS selector expressions. These expressions often result in a more
1682 * compact representation of the desired result.
1683
1684 * @param {Node} root The root of the tree to search.
1685 * @param {function(Node) : boolean} p The filter function.
1686 * @return {!Array<!Node>} The found nodes or an empty array if none are found.
1687 */
1688goog.dom.findNodes = function(root, p) {
1689 var rv = [];
1690 goog.dom.findNodes_(root, p, rv, false);
1691 return rv;
1692};
1693
1694
1695/**
1696 * Finds the first or all the descendant nodes that match the filter function,
1697 * using a depth first search.
1698 * @param {Node} root The root of the tree to search.
1699 * @param {function(Node) : boolean} p The filter function.
1700 * @param {!Array<!Node>} rv The found nodes are added to this array.
1701 * @param {boolean} findOne If true we exit after the first found node.
1702 * @return {boolean} Whether the search is complete or not. True in case findOne
1703 * is true and the node is found. False otherwise.
1704 * @private
1705 */
1706goog.dom.findNodes_ = function(root, p, rv, findOne) {
1707 if (root != null) {
1708 var child = root.firstChild;
1709 while (child) {
1710 if (p(child)) {
1711 rv.push(child);
1712 if (findOne) {
1713 return true;
1714 }
1715 }
1716 if (goog.dom.findNodes_(child, p, rv, findOne)) {
1717 return true;
1718 }
1719 child = child.nextSibling;
1720 }
1721 }
1722 return false;
1723};
1724
1725
1726/**
1727 * Map of tags whose content to ignore when calculating text length.
1728 * @private {!Object<string, number>}
1729 * @const
1730 */
1731goog.dom.TAGS_TO_IGNORE_ = {
1732 'SCRIPT': 1,
1733 'STYLE': 1,
1734 'HEAD': 1,
1735 'IFRAME': 1,
1736 'OBJECT': 1
1737};
1738
1739
1740/**
1741 * Map of tags which have predefined values with regard to whitespace.
1742 * @private {!Object<string, string>}
1743 * @const
1744 */
1745goog.dom.PREDEFINED_TAG_VALUES_ = {'IMG': ' ', 'BR': '\n'};
1746
1747
1748/**
1749 * Returns true if the element has a tab index that allows it to receive
1750 * keyboard focus (tabIndex >= 0), false otherwise. Note that some elements
1751 * natively support keyboard focus, even if they have no tab index.
1752 * @param {!Element} element Element to check.
1753 * @return {boolean} Whether the element has a tab index that allows keyboard
1754 * focus.
1755 * @see http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
1756 */
1757goog.dom.isFocusableTabIndex = function(element) {
1758 return goog.dom.hasSpecifiedTabIndex_(element) &&
1759 goog.dom.isTabIndexFocusable_(element);
1760};
1761
1762
1763/**
1764 * Enables or disables keyboard focus support on the element via its tab index.
1765 * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true
1766 * (or elements that natively support keyboard focus, like form elements) can
1767 * receive keyboard focus. See http://go/tabindex for more info.
1768 * @param {Element} element Element whose tab index is to be changed.
1769 * @param {boolean} enable Whether to set or remove a tab index on the element
1770 * that supports keyboard focus.
1771 */
1772goog.dom.setFocusableTabIndex = function(element, enable) {
1773 if (enable) {
1774 element.tabIndex = 0;
1775 } else {
1776 // Set tabIndex to -1 first, then remove it. This is a workaround for
1777 // Safari (confirmed in version 4 on Windows). When removing the attribute
1778 // without setting it to -1 first, the element remains keyboard focusable
1779 // despite not having a tabIndex attribute anymore.
1780 element.tabIndex = -1;
1781 element.removeAttribute('tabIndex'); // Must be camelCase!
1782 }
1783};
1784
1785
1786/**
1787 * Returns true if the element can be focused, i.e. it has a tab index that
1788 * allows it to receive keyboard focus (tabIndex >= 0), or it is an element
1789 * that natively supports keyboard focus.
1790 * @param {!Element} element Element to check.
1791 * @return {boolean} Whether the element allows keyboard focus.
1792 */
1793goog.dom.isFocusable = function(element) {
1794 var focusable;
1795 // Some elements can have unspecified tab index and still receive focus.
1796 if (goog.dom.nativelySupportsFocus_(element)) {
1797 // Make sure the element is not disabled ...
1798 focusable = !element.disabled &&
1799 // ... and if a tab index is specified, it allows focus.
1800 (!goog.dom.hasSpecifiedTabIndex_(element) ||
1801 goog.dom.isTabIndexFocusable_(element));
1802 } else {
1803 focusable = goog.dom.isFocusableTabIndex(element);
1804 }
1805
1806 // IE requires elements to be visible in order to focus them.
1807 return focusable && goog.userAgent.IE ?
1808 goog.dom.hasNonZeroBoundingRect_(element) : focusable;
1809};
1810
1811
1812/**
1813 * Returns true if the element has a specified tab index.
1814 * @param {!Element} element Element to check.
1815 * @return {boolean} Whether the element has a specified tab index.
1816 * @private
1817 */
1818goog.dom.hasSpecifiedTabIndex_ = function(element) {
1819 // IE returns 0 for an unset tabIndex, so we must use getAttributeNode(),
1820 // which returns an object with a 'specified' property if tabIndex is
1821 // specified. This works on other browsers, too.
1822 var attrNode = element.getAttributeNode('tabindex'); // Must be lowercase!
1823 return goog.isDefAndNotNull(attrNode) && attrNode.specified;
1824};
1825
1826
1827/**
1828 * Returns true if the element's tab index allows the element to be focused.
1829 * @param {!Element} element Element to check.
1830 * @return {boolean} Whether the element's tab index allows focus.
1831 * @private
1832 */
1833goog.dom.isTabIndexFocusable_ = function(element) {
1834 var index = element.tabIndex;
1835 // NOTE: IE9 puts tabIndex in 16-bit int, e.g. -2 is 65534.
1836 return goog.isNumber(index) && index >= 0 && index < 32768;
1837};
1838
1839
1840/**
1841 * Returns true if the element is focusable even when tabIndex is not set.
1842 * @param {!Element} element Element to check.
1843 * @return {boolean} Whether the element natively supports focus.
1844 * @private
1845 */
1846goog.dom.nativelySupportsFocus_ = function(element) {
1847 return element.tagName == goog.dom.TagName.A ||
1848 element.tagName == goog.dom.TagName.INPUT ||
1849 element.tagName == goog.dom.TagName.TEXTAREA ||
1850 element.tagName == goog.dom.TagName.SELECT ||
1851 element.tagName == goog.dom.TagName.BUTTON;
1852};
1853
1854
1855/**
1856 * Returns true if the element has a bounding rectangle that would be visible
1857 * (i.e. its width and height are greater than zero).
1858 * @param {!Element} element Element to check.
1859 * @return {boolean} Whether the element has a non-zero bounding rectangle.
1860 * @private
1861 */
1862goog.dom.hasNonZeroBoundingRect_ = function(element) {
1863 var rect = goog.isFunction(element['getBoundingClientRect']) ?
1864 element.getBoundingClientRect() :
1865 {'height': element.offsetHeight, 'width': element.offsetWidth};
1866 return goog.isDefAndNotNull(rect) && rect.height > 0 && rect.width > 0;
1867};
1868
1869
1870/**
1871 * Returns the text content of the current node, without markup and invisible
1872 * symbols. New lines are stripped and whitespace is collapsed,
1873 * such that each character would be visible.
1874 *
1875 * In browsers that support it, innerText is used. Other browsers attempt to
1876 * simulate it via node traversal. Line breaks are canonicalized in IE.
1877 *
1878 * @param {Node} node The node from which we are getting content.
1879 * @return {string} The text content.
1880 */
1881goog.dom.getTextContent = function(node) {
1882 var textContent;
1883 // Note(arv): IE9, Opera, and Safari 3 support innerText but they include
1884 // text nodes in script tags. So we revert to use a user agent test here.
1885 if (goog.dom.BrowserFeature.CAN_USE_INNER_TEXT && ('innerText' in node)) {
1886 textContent = goog.string.canonicalizeNewlines(node.innerText);
1887 // Unfortunately .innerText() returns text with &shy; symbols
1888 // We need to filter it out and then remove duplicate whitespaces
1889 } else {
1890 var buf = [];
1891 goog.dom.getTextContent_(node, buf, true);
1892 textContent = buf.join('');
1893 }
1894
1895 // Strip &shy; entities. goog.format.insertWordBreaks inserts them in Opera.
1896 textContent = textContent.replace(/ \xAD /g, ' ').replace(/\xAD/g, '');
1897 // Strip &#8203; entities. goog.format.insertWordBreaks inserts them in IE8.
1898 textContent = textContent.replace(/\u200B/g, '');
1899
1900 // Skip this replacement on old browsers with working innerText, which
1901 // automatically turns &nbsp; into ' ' and / +/ into ' ' when reading
1902 // innerText.
1903 if (!goog.dom.BrowserFeature.CAN_USE_INNER_TEXT) {
1904 textContent = textContent.replace(/ +/g, ' ');
1905 }
1906 if (textContent != ' ') {
1907 textContent = textContent.replace(/^\s*/, '');
1908 }
1909
1910 return textContent;
1911};
1912
1913
1914/**
1915 * Returns the text content of the current node, without markup.
1916 *
1917 * Unlike {@code getTextContent} this method does not collapse whitespaces
1918 * or normalize lines breaks.
1919 *
1920 * @param {Node} node The node from which we are getting content.
1921 * @return {string} The raw text content.
1922 */
1923goog.dom.getRawTextContent = function(node) {
1924 var buf = [];
1925 goog.dom.getTextContent_(node, buf, false);
1926
1927 return buf.join('');
1928};
1929
1930
1931/**
1932 * Recursive support function for text content retrieval.
1933 *
1934 * @param {Node} node The node from which we are getting content.
1935 * @param {Array<string>} buf string buffer.
1936 * @param {boolean} normalizeWhitespace Whether to normalize whitespace.
1937 * @private
1938 */
1939goog.dom.getTextContent_ = function(node, buf, normalizeWhitespace) {
1940 if (node.nodeName in goog.dom.TAGS_TO_IGNORE_) {
1941 // ignore certain tags
1942 } else if (node.nodeType == goog.dom.NodeType.TEXT) {
1943 if (normalizeWhitespace) {
1944 buf.push(String(node.nodeValue).replace(/(\r\n|\r|\n)/g, ''));
1945 } else {
1946 buf.push(node.nodeValue);
1947 }
1948 } else if (node.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {
1949 buf.push(goog.dom.PREDEFINED_TAG_VALUES_[node.nodeName]);
1950 } else {
1951 var child = node.firstChild;
1952 while (child) {
1953 goog.dom.getTextContent_(child, buf, normalizeWhitespace);
1954 child = child.nextSibling;
1955 }
1956 }
1957};
1958
1959
1960/**
1961 * Returns the text length of the text contained in a node, without markup. This
1962 * is equivalent to the selection length if the node was selected, or the number
1963 * of cursor movements to traverse the node. Images & BRs take one space. New
1964 * lines are ignored.
1965 *
1966 * @param {Node} node The node whose text content length is being calculated.
1967 * @return {number} The length of {@code node}'s text content.
1968 */
1969goog.dom.getNodeTextLength = function(node) {
1970 return goog.dom.getTextContent(node).length;
1971};
1972
1973
1974/**
1975 * Returns the text offset of a node relative to one of its ancestors. The text
1976 * length is the same as the length calculated by goog.dom.getNodeTextLength.
1977 *
1978 * @param {Node} node The node whose offset is being calculated.
1979 * @param {Node=} opt_offsetParent The node relative to which the offset will
1980 * be calculated. Defaults to the node's owner document's body.
1981 * @return {number} The text offset.
1982 */
1983goog.dom.getNodeTextOffset = function(node, opt_offsetParent) {
1984 var root = opt_offsetParent || goog.dom.getOwnerDocument(node).body;
1985 var buf = [];
1986 while (node && node != root) {
1987 var cur = node;
1988 while ((cur = cur.previousSibling)) {
1989 buf.unshift(goog.dom.getTextContent(cur));
1990 }
1991 node = node.parentNode;
1992 }
1993 // Trim left to deal with FF cases when there might be line breaks and empty
1994 // nodes at the front of the text
1995 return goog.string.trimLeft(buf.join('')).replace(/ +/g, ' ').length;
1996};
1997
1998
1999/**
2000 * Returns the node at a given offset in a parent node. If an object is
2001 * provided for the optional third parameter, the node and the remainder of the
2002 * offset will stored as properties of this object.
2003 * @param {Node} parent The parent node.
2004 * @param {number} offset The offset into the parent node.
2005 * @param {Object=} opt_result Object to be used to store the return value. The
2006 * return value will be stored in the form {node: Node, remainder: number}
2007 * if this object is provided.
2008 * @return {Node} The node at the given offset.
2009 */
2010goog.dom.getNodeAtOffset = function(parent, offset, opt_result) {
2011 var stack = [parent], pos = 0, cur = null;
2012 while (stack.length > 0 && pos < offset) {
2013 cur = stack.pop();
2014 if (cur.nodeName in goog.dom.TAGS_TO_IGNORE_) {
2015 // ignore certain tags
2016 } else if (cur.nodeType == goog.dom.NodeType.TEXT) {
2017 var text = cur.nodeValue.replace(/(\r\n|\r|\n)/g, '').replace(/ +/g, ' ');
2018 pos += text.length;
2019 } else if (cur.nodeName in goog.dom.PREDEFINED_TAG_VALUES_) {
2020 pos += goog.dom.PREDEFINED_TAG_VALUES_[cur.nodeName].length;
2021 } else {
2022 for (var i = cur.childNodes.length - 1; i >= 0; i--) {
2023 stack.push(cur.childNodes[i]);
2024 }
2025 }
2026 }
2027 if (goog.isObject(opt_result)) {
2028 opt_result.remainder = cur ? cur.nodeValue.length + offset - pos - 1 : 0;
2029 opt_result.node = cur;
2030 }
2031
2032 return cur;
2033};
2034
2035
2036/**
2037 * Returns true if the object is a {@code NodeList}. To qualify as a NodeList,
2038 * the object must have a numeric length property and an item function (which
2039 * has type 'string' on IE for some reason).
2040 * @param {Object} val Object to test.
2041 * @return {boolean} Whether the object is a NodeList.
2042 */
2043goog.dom.isNodeList = function(val) {
2044 // TODO(attila): Now the isNodeList is part of goog.dom we can use
2045 // goog.userAgent to make this simpler.
2046 // A NodeList must have a length property of type 'number' on all platforms.
2047 if (val && typeof val.length == 'number') {
2048 // A NodeList is an object everywhere except Safari, where it's a function.
2049 if (goog.isObject(val)) {
2050 // A NodeList must have an item function (on non-IE platforms) or an item
2051 // property of type 'string' (on IE).
2052 return typeof val.item == 'function' || typeof val.item == 'string';
2053 } else if (goog.isFunction(val)) {
2054 // On Safari, a NodeList is a function with an item property that is also
2055 // a function.
2056 return typeof val.item == 'function';
2057 }
2058 }
2059
2060 // Not a NodeList.
2061 return false;
2062};
2063
2064
2065/**
2066 * Walks up the DOM hierarchy returning the first ancestor that has the passed
2067 * tag name and/or class name. If the passed element matches the specified
2068 * criteria, the element itself is returned.
2069 * @param {Node} element The DOM node to start with.
2070 * @param {?(goog.dom.TagName|string)=} opt_tag The tag name to match (or
2071 * null/undefined to match only based on class name).
2072 * @param {?string=} opt_class The class name to match (or null/undefined to
2073 * match only based on tag name).
2074 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
2075 * dom.
2076 * @return {Element} The first ancestor that matches the passed criteria, or
2077 * null if no match is found.
2078 */
2079goog.dom.getAncestorByTagNameAndClass = function(element, opt_tag, opt_class,
2080 opt_maxSearchSteps) {
2081 if (!opt_tag && !opt_class) {
2082 return null;
2083 }
2084 var tagName = opt_tag ? opt_tag.toUpperCase() : null;
2085 return /** @type {Element} */ (goog.dom.getAncestor(element,
2086 function(node) {
2087 return (!tagName || node.nodeName == tagName) &&
2088 (!opt_class || goog.isString(node.className) &&
2089 goog.array.contains(node.className.split(/\s+/), opt_class));
2090 }, true, opt_maxSearchSteps));
2091};
2092
2093
2094/**
2095 * Walks up the DOM hierarchy returning the first ancestor that has the passed
2096 * class name. If the passed element matches the specified criteria, the
2097 * element itself is returned.
2098 * @param {Node} element The DOM node to start with.
2099 * @param {string} className The class name to match.
2100 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
2101 * dom.
2102 * @return {Element} The first ancestor that matches the passed criteria, or
2103 * null if none match.
2104 */
2105goog.dom.getAncestorByClass = function(element, className, opt_maxSearchSteps) {
2106 return goog.dom.getAncestorByTagNameAndClass(element, null, className,
2107 opt_maxSearchSteps);
2108};
2109
2110
2111/**
2112 * Walks up the DOM hierarchy returning the first ancestor that passes the
2113 * matcher function.
2114 * @param {Node} element The DOM node to start with.
2115 * @param {function(Node) : boolean} matcher A function that returns true if the
2116 * passed node matches the desired criteria.
2117 * @param {boolean=} opt_includeNode If true, the node itself is included in
2118 * the search (the first call to the matcher will pass startElement as
2119 * the node to test).
2120 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
2121 * dom.
2122 * @return {Node} DOM node that matched the matcher, or null if there was
2123 * no match.
2124 */
2125goog.dom.getAncestor = function(
2126 element, matcher, opt_includeNode, opt_maxSearchSteps) {
2127 if (!opt_includeNode) {
2128 element = element.parentNode;
2129 }
2130 var ignoreSearchSteps = opt_maxSearchSteps == null;
2131 var steps = 0;
2132 while (element && (ignoreSearchSteps || steps <= opt_maxSearchSteps)) {
2133 goog.asserts.assert(element.name != 'parentNode');
2134 if (matcher(element)) {
2135 return element;
2136 }
2137 element = element.parentNode;
2138 steps++;
2139 }
2140 // Reached the root of the DOM without a match
2141 return null;
2142};
2143
2144
2145/**
2146 * Determines the active element in the given document.
2147 * @param {Document} doc The document to look in.
2148 * @return {Element} The active element.
2149 */
2150goog.dom.getActiveElement = function(doc) {
2151 try {
2152 return doc && doc.activeElement;
2153 } catch (e) {
2154 // NOTE(nicksantos): Sometimes, evaluating document.activeElement in IE
2155 // throws an exception. I'm not 100% sure why, but I suspect it chokes
2156 // on document.activeElement if the activeElement has been recently
2157 // removed from the DOM by a JS operation.
2158 //
2159 // We assume that an exception here simply means
2160 // "there is no active element."
2161 }
2162
2163 return null;
2164};
2165
2166
2167/**
2168 * Gives the current devicePixelRatio.
2169 *
2170 * By default, this is the value of window.devicePixelRatio (which should be
2171 * preferred if present).
2172 *
2173 * If window.devicePixelRatio is not present, the ratio is calculated with
2174 * window.matchMedia, if present. Otherwise, gives 1.0.
2175 *
2176 * Some browsers (including Chrome) consider the browser zoom level in the pixel
2177 * ratio, so the value may change across multiple calls.
2178 *
2179 * @return {number} The number of actual pixels per virtual pixel.
2180 */
2181goog.dom.getPixelRatio = function() {
2182 var win = goog.dom.getWindow();
2183
2184 // devicePixelRatio does not work on Mobile firefox.
2185 // TODO(user): Enable this check on a known working mobile Gecko version.
2186 // Filed a bug: https://bugzilla.mozilla.org/show_bug.cgi?id=896804
2187 var isFirefoxMobile = goog.userAgent.GECKO && goog.userAgent.MOBILE;
2188
2189 if (goog.isDef(win.devicePixelRatio) && !isFirefoxMobile) {
2190 return win.devicePixelRatio;
2191 } else if (win.matchMedia) {
2192 return goog.dom.matchesPixelRatio_(.75) ||
2193 goog.dom.matchesPixelRatio_(1.5) ||
2194 goog.dom.matchesPixelRatio_(2) ||
2195 goog.dom.matchesPixelRatio_(3) || 1;
2196 }
2197 return 1;
2198};
2199
2200
2201/**
2202 * Calculates a mediaQuery to check if the current device supports the
2203 * given actual to virtual pixel ratio.
2204 * @param {number} pixelRatio The ratio of actual pixels to virtual pixels.
2205 * @return {number} pixelRatio if applicable, otherwise 0.
2206 * @private
2207 */
2208goog.dom.matchesPixelRatio_ = function(pixelRatio) {
2209 var win = goog.dom.getWindow();
2210 var query = ('(-webkit-min-device-pixel-ratio: ' + pixelRatio + '),' +
2211 '(min--moz-device-pixel-ratio: ' + pixelRatio + '),' +
2212 '(min-resolution: ' + pixelRatio + 'dppx)');
2213 return win.matchMedia(query).matches ? pixelRatio : 0;
2214};
2215
2216
2217
2218/**
2219 * Create an instance of a DOM helper with a new document object.
2220 * @param {Document=} opt_document Document object to associate with this
2221 * DOM helper.
2222 * @constructor
2223 */
2224goog.dom.DomHelper = function(opt_document) {
2225 /**
2226 * Reference to the document object to use
2227 * @type {!Document}
2228 * @private
2229 */
2230 this.document_ = opt_document || goog.global.document || document;
2231};
2232
2233
2234/**
2235 * Gets the dom helper object for the document where the element resides.
2236 * @param {Node=} opt_node If present, gets the DomHelper for this node.
2237 * @return {!goog.dom.DomHelper} The DomHelper.
2238 */
2239goog.dom.DomHelper.prototype.getDomHelper = goog.dom.getDomHelper;
2240
2241
2242/**
2243 * Sets the document object.
2244 * @param {!Document} document Document object.
2245 */
2246goog.dom.DomHelper.prototype.setDocument = function(document) {
2247 this.document_ = document;
2248};
2249
2250
2251/**
2252 * Gets the document object being used by the dom library.
2253 * @return {!Document} Document object.
2254 */
2255goog.dom.DomHelper.prototype.getDocument = function() {
2256 return this.document_;
2257};
2258
2259
2260/**
2261 * Alias for {@code getElementById}. If a DOM node is passed in then we just
2262 * return that.
2263 * @param {string|Element} element Element ID or a DOM node.
2264 * @return {Element} The element with the given ID, or the node passed in.
2265 */
2266goog.dom.DomHelper.prototype.getElement = function(element) {
2267 return goog.dom.getElementHelper_(this.document_, element);
2268};
2269
2270
2271/**
2272 * Gets an element by id, asserting that the element is found.
2273 *
2274 * This is used when an element is expected to exist, and should fail with
2275 * an assertion error if it does not (if assertions are enabled).
2276 *
2277 * @param {string} id Element ID.
2278 * @return {!Element} The element with the given ID, if it exists.
2279 */
2280goog.dom.DomHelper.prototype.getRequiredElement = function(id) {
2281 return goog.dom.getRequiredElementHelper_(this.document_, id);
2282};
2283
2284
2285/**
2286 * Alias for {@code getElement}.
2287 * @param {string|Element} element Element ID or a DOM node.
2288 * @return {Element} The element with the given ID, or the node passed in.
2289 * @deprecated Use {@link goog.dom.DomHelper.prototype.getElement} instead.
2290 */
2291goog.dom.DomHelper.prototype.$ = goog.dom.DomHelper.prototype.getElement;
2292
2293
2294/**
2295 * Looks up elements by both tag and class name, using browser native functions
2296 * ({@code querySelectorAll}, {@code getElementsByTagName} or
2297 * {@code getElementsByClassName}) where possible. The returned array is a live
2298 * NodeList or a static list depending on the code path taken.
2299 *
2300 * @see goog.dom.query
2301 *
2302 * @param {?string=} opt_tag Element tag name or * for all tags.
2303 * @param {?string=} opt_class Optional class name.
2304 * @param {(Document|Element)=} opt_el Optional element to look in.
2305 * @return { {length: number} } Array-like list of elements (only a length
2306 * property and numerical indices are guaranteed to exist).
2307 */
2308goog.dom.DomHelper.prototype.getElementsByTagNameAndClass = function(opt_tag,
2309 opt_class,
2310 opt_el) {
2311 return goog.dom.getElementsByTagNameAndClass_(this.document_, opt_tag,
2312 opt_class, opt_el);
2313};
2314
2315
2316/**
2317 * Returns an array of all the elements with the provided className.
2318 * @see {goog.dom.query}
2319 * @param {string} className the name of the class to look for.
2320 * @param {Element|Document=} opt_el Optional element to look in.
2321 * @return { {length: number} } The items found with the class name provided.
2322 */
2323goog.dom.DomHelper.prototype.getElementsByClass = function(className, opt_el) {
2324 var doc = opt_el || this.document_;
2325 return goog.dom.getElementsByClass(className, doc);
2326};
2327
2328
2329/**
2330 * Returns the first element we find matching the provided class name.
2331 * @see {goog.dom.query}
2332 * @param {string} className the name of the class to look for.
2333 * @param {(Element|Document)=} opt_el Optional element to look in.
2334 * @return {Element} The first item found with the class name provided.
2335 */
2336goog.dom.DomHelper.prototype.getElementByClass = function(className, opt_el) {
2337 var doc = opt_el || this.document_;
2338 return goog.dom.getElementByClass(className, doc);
2339};
2340
2341
2342/**
2343 * Ensures an element with the given className exists, and then returns the
2344 * first element with the provided className.
2345 * @see {goog.dom.query}
2346 * @param {string} className the name of the class to look for.
2347 * @param {(!Element|!Document)=} opt_root Optional element or document to look
2348 * in.
2349 * @return {!Element} The first item found with the class name provided.
2350 * @throws {goog.asserts.AssertionError} Thrown if no element is found.
2351 */
2352goog.dom.DomHelper.prototype.getRequiredElementByClass = function(className,
2353 opt_root) {
2354 var root = opt_root || this.document_;
2355 return goog.dom.getRequiredElementByClass(className, root);
2356};
2357
2358
2359/**
2360 * Alias for {@code getElementsByTagNameAndClass}.
2361 * @deprecated Use DomHelper getElementsByTagNameAndClass.
2362 * @see goog.dom.query
2363 *
2364 * @param {?string=} opt_tag Element tag name.
2365 * @param {?string=} opt_class Optional class name.
2366 * @param {Element=} opt_el Optional element to look in.
2367 * @return { {length: number} } Array-like list of elements (only a length
2368 * property and numerical indices are guaranteed to exist).
2369 */
2370goog.dom.DomHelper.prototype.$$ =
2371 goog.dom.DomHelper.prototype.getElementsByTagNameAndClass;
2372
2373
2374/**
2375 * Sets a number of properties on a node.
2376 * @param {Element} element DOM node to set properties on.
2377 * @param {Object} properties Hash of property:value pairs.
2378 */
2379goog.dom.DomHelper.prototype.setProperties = goog.dom.setProperties;
2380
2381
2382/**
2383 * Gets the dimensions of the viewport.
2384 * @param {Window=} opt_window Optional window element to test. Defaults to
2385 * the window of the Dom Helper.
2386 * @return {!goog.math.Size} Object with values 'width' and 'height'.
2387 */
2388goog.dom.DomHelper.prototype.getViewportSize = function(opt_window) {
2389 // TODO(arv): This should not take an argument. That breaks the rule of a
2390 // a DomHelper representing a single frame/window/document.
2391 return goog.dom.getViewportSize(opt_window || this.getWindow());
2392};
2393
2394
2395/**
2396 * Calculates the height of the document.
2397 *
2398 * @return {number} The height of the document.
2399 */
2400goog.dom.DomHelper.prototype.getDocumentHeight = function() {
2401 return goog.dom.getDocumentHeight_(this.getWindow());
2402};
2403
2404
2405/**
2406 * Typedef for use with goog.dom.createDom and goog.dom.append.
2407 * @typedef {Object|string|Array|NodeList}
2408 */
2409goog.dom.Appendable;
2410
2411
2412/**
2413 * Returns a dom node with a set of attributes. This function accepts varargs
2414 * for subsequent nodes to be added. Subsequent nodes will be added to the
2415 * first node as childNodes.
2416 *
2417 * So:
2418 * <code>createDom('div', null, createDom('p'), createDom('p'));</code>
2419 * would return a div with two child paragraphs
2420 *
2421 * An easy way to move all child nodes of an existing element to a new parent
2422 * element is:
2423 * <code>createDom('div', null, oldElement.childNodes);</code>
2424 * which will remove all child nodes from the old element and add them as
2425 * child nodes of the new DIV.
2426 *
2427 * @param {string} tagName Tag to create.
2428 * @param {Object|string=} opt_attributes If object, then a map of name-value
2429 * pairs for attributes. If a string, then this is the className of the new
2430 * element.
2431 * @param {...goog.dom.Appendable} var_args Further DOM nodes or
2432 * strings for text nodes. If one of the var_args is an array or
2433 * NodeList, its elements will be added as childNodes instead.
2434 * @return {!Element} Reference to a DOM node.
2435 */
2436goog.dom.DomHelper.prototype.createDom = function(tagName,
2437 opt_attributes,
2438 var_args) {
2439 return goog.dom.createDom_(this.document_, arguments);
2440};
2441
2442
2443/**
2444 * Alias for {@code createDom}.
2445 * @param {string} tagName Tag to create.
2446 * @param {(Object|string)=} opt_attributes If object, then a map of name-value
2447 * pairs for attributes. If a string, then this is the className of the new
2448 * element.
2449 * @param {...goog.dom.Appendable} var_args Further DOM nodes or strings for
2450 * text nodes. If one of the var_args is an array, its children will be
2451 * added as childNodes instead.
2452 * @return {!Element} Reference to a DOM node.
2453 * @deprecated Use {@link goog.dom.DomHelper.prototype.createDom} instead.
2454 */
2455goog.dom.DomHelper.prototype.$dom = goog.dom.DomHelper.prototype.createDom;
2456
2457
2458/**
2459 * Creates a new element.
2460 * @param {string} name Tag name.
2461 * @return {!Element} The new element.
2462 */
2463goog.dom.DomHelper.prototype.createElement = function(name) {
2464 return this.document_.createElement(name);
2465};
2466
2467
2468/**
2469 * Creates a new text node.
2470 * @param {number|string} content Content.
2471 * @return {!Text} The new text node.
2472 */
2473goog.dom.DomHelper.prototype.createTextNode = function(content) {
2474 return this.document_.createTextNode(String(content));
2475};
2476
2477
2478/**
2479 * Create a table.
2480 * @param {number} rows The number of rows in the table. Must be >= 1.
2481 * @param {number} columns The number of columns in the table. Must be >= 1.
2482 * @param {boolean=} opt_fillWithNbsp If true, fills table entries with
2483 * {@code goog.string.Unicode.NBSP} characters.
2484 * @return {!HTMLElement} The created table.
2485 */
2486goog.dom.DomHelper.prototype.createTable = function(rows, columns,
2487 opt_fillWithNbsp) {
2488 return goog.dom.createTable_(this.document_, rows, columns,
2489 !!opt_fillWithNbsp);
2490};
2491
2492
2493/**
2494 * Converts an HTML into a node or a document fragment. A single Node is used if
2495 * {@code html} only generates a single node. If {@code html} generates multiple
2496 * nodes then these are put inside a {@code DocumentFragment}.
2497 * @param {!goog.html.SafeHtml} html The HTML markup to convert.
2498 * @return {!Node} The resulting node.
2499 */
2500goog.dom.DomHelper.prototype.safeHtmlToNode = function(html) {
2501 return goog.dom.safeHtmlToNode_(this.document_, html);
2502};
2503
2504
2505/**
2506 * Converts an HTML string into a node or a document fragment. A single Node
2507 * is used if the {@code htmlString} only generates a single node. If the
2508 * {@code htmlString} generates multiple nodes then these are put inside a
2509 * {@code DocumentFragment}.
2510 *
2511 * @param {string} htmlString The HTML string to convert.
2512 * @return {!Node} The resulting node.
2513 */
2514goog.dom.DomHelper.prototype.htmlToDocumentFragment = function(htmlString) {
2515 return goog.dom.htmlToDocumentFragment_(this.document_, htmlString);
2516};
2517
2518
2519/**
2520 * Returns true if the browser is in "CSS1-compatible" (standards-compliant)
2521 * mode, false otherwise.
2522 * @return {boolean} True if in CSS1-compatible mode.
2523 */
2524goog.dom.DomHelper.prototype.isCss1CompatMode = function() {
2525 return goog.dom.isCss1CompatMode_(this.document_);
2526};
2527
2528
2529/**
2530 * Gets the window object associated with the document.
2531 * @return {!Window} The window associated with the given document.
2532 */
2533goog.dom.DomHelper.prototype.getWindow = function() {
2534 return goog.dom.getWindow_(this.document_);
2535};
2536
2537
2538/**
2539 * Gets the document scroll element.
2540 * @return {!Element} Scrolling element.
2541 */
2542goog.dom.DomHelper.prototype.getDocumentScrollElement = function() {
2543 return goog.dom.getDocumentScrollElement_(this.document_);
2544};
2545
2546
2547/**
2548 * Gets the document scroll distance as a coordinate object.
2549 * @return {!goog.math.Coordinate} Object with properties 'x' and 'y'.
2550 */
2551goog.dom.DomHelper.prototype.getDocumentScroll = function() {
2552 return goog.dom.getDocumentScroll_(this.document_);
2553};
2554
2555
2556/**
2557 * Determines the active element in the given document.
2558 * @param {Document=} opt_doc The document to look in.
2559 * @return {Element} The active element.
2560 */
2561goog.dom.DomHelper.prototype.getActiveElement = function(opt_doc) {
2562 return goog.dom.getActiveElement(opt_doc || this.document_);
2563};
2564
2565
2566/**
2567 * Appends a child to a node.
2568 * @param {Node} parent Parent.
2569 * @param {Node} child Child.
2570 */
2571goog.dom.DomHelper.prototype.appendChild = goog.dom.appendChild;
2572
2573
2574/**
2575 * Appends a node with text or other nodes.
2576 * @param {!Node} parent The node to append nodes to.
2577 * @param {...goog.dom.Appendable} var_args The things to append to the node.
2578 * If this is a Node it is appended as is.
2579 * If this is a string then a text node is appended.
2580 * If this is an array like object then fields 0 to length - 1 are appended.
2581 */
2582goog.dom.DomHelper.prototype.append = goog.dom.append;
2583
2584
2585/**
2586 * Determines if the given node can contain children, intended to be used for
2587 * HTML generation.
2588 *
2589 * @param {Node} node The node to check.
2590 * @return {boolean} Whether the node can contain children.
2591 */
2592goog.dom.DomHelper.prototype.canHaveChildren = goog.dom.canHaveChildren;
2593
2594
2595/**
2596 * Removes all the child nodes on a DOM node.
2597 * @param {Node} node Node to remove children from.
2598 */
2599goog.dom.DomHelper.prototype.removeChildren = goog.dom.removeChildren;
2600
2601
2602/**
2603 * Inserts a new node before an existing reference node (i.e., as the previous
2604 * sibling). If the reference node has no parent, then does nothing.
2605 * @param {Node} newNode Node to insert.
2606 * @param {Node} refNode Reference node to insert before.
2607 */
2608goog.dom.DomHelper.prototype.insertSiblingBefore = goog.dom.insertSiblingBefore;
2609
2610
2611/**
2612 * Inserts a new node after an existing reference node (i.e., as the next
2613 * sibling). If the reference node has no parent, then does nothing.
2614 * @param {Node} newNode Node to insert.
2615 * @param {Node} refNode Reference node to insert after.
2616 */
2617goog.dom.DomHelper.prototype.insertSiblingAfter = goog.dom.insertSiblingAfter;
2618
2619
2620/**
2621 * Insert a child at a given index. If index is larger than the number of child
2622 * nodes that the parent currently has, the node is inserted as the last child
2623 * node.
2624 * @param {Element} parent The element into which to insert the child.
2625 * @param {Node} child The element to insert.
2626 * @param {number} index The index at which to insert the new child node. Must
2627 * not be negative.
2628 */
2629goog.dom.DomHelper.prototype.insertChildAt = goog.dom.insertChildAt;
2630
2631
2632/**
2633 * Removes a node from its parent.
2634 * @param {Node} node The node to remove.
2635 * @return {Node} The node removed if removed; else, null.
2636 */
2637goog.dom.DomHelper.prototype.removeNode = goog.dom.removeNode;
2638
2639
2640/**
2641 * Replaces a node in the DOM tree. Will do nothing if {@code oldNode} has no
2642 * parent.
2643 * @param {Node} newNode Node to insert.
2644 * @param {Node} oldNode Node to replace.
2645 */
2646goog.dom.DomHelper.prototype.replaceNode = goog.dom.replaceNode;
2647
2648
2649/**
2650 * Flattens an element. That is, removes it and replace it with its children.
2651 * @param {Element} element The element to flatten.
2652 * @return {Element|undefined} The original element, detached from the document
2653 * tree, sans children, or undefined if the element was already not in the
2654 * document.
2655 */
2656goog.dom.DomHelper.prototype.flattenElement = goog.dom.flattenElement;
2657
2658
2659/**
2660 * Returns an array containing just the element children of the given element.
2661 * @param {Element} element The element whose element children we want.
2662 * @return {!(Array|NodeList)} An array or array-like list of just the element
2663 * children of the given element.
2664 */
2665goog.dom.DomHelper.prototype.getChildren = goog.dom.getChildren;
2666
2667
2668/**
2669 * Returns the first child node that is an element.
2670 * @param {Node} node The node to get the first child element of.
2671 * @return {Element} The first child node of {@code node} that is an element.
2672 */
2673goog.dom.DomHelper.prototype.getFirstElementChild =
2674 goog.dom.getFirstElementChild;
2675
2676
2677/**
2678 * Returns the last child node that is an element.
2679 * @param {Node} node The node to get the last child element of.
2680 * @return {Element} The last child node of {@code node} that is an element.
2681 */
2682goog.dom.DomHelper.prototype.getLastElementChild = goog.dom.getLastElementChild;
2683
2684
2685/**
2686 * Returns the first next sibling that is an element.
2687 * @param {Node} node The node to get the next sibling element of.
2688 * @return {Element} The next sibling of {@code node} that is an element.
2689 */
2690goog.dom.DomHelper.prototype.getNextElementSibling =
2691 goog.dom.getNextElementSibling;
2692
2693
2694/**
2695 * Returns the first previous sibling that is an element.
2696 * @param {Node} node The node to get the previous sibling element of.
2697 * @return {Element} The first previous sibling of {@code node} that is
2698 * an element.
2699 */
2700goog.dom.DomHelper.prototype.getPreviousElementSibling =
2701 goog.dom.getPreviousElementSibling;
2702
2703
2704/**
2705 * Returns the next node in source order from the given node.
2706 * @param {Node} node The node.
2707 * @return {Node} The next node in the DOM tree, or null if this was the last
2708 * node.
2709 */
2710goog.dom.DomHelper.prototype.getNextNode = goog.dom.getNextNode;
2711
2712
2713/**
2714 * Returns the previous node in source order from the given node.
2715 * @param {Node} node The node.
2716 * @return {Node} The previous node in the DOM tree, or null if this was the
2717 * first node.
2718 */
2719goog.dom.DomHelper.prototype.getPreviousNode = goog.dom.getPreviousNode;
2720
2721
2722/**
2723 * Whether the object looks like a DOM node.
2724 * @param {?} obj The object being tested for node likeness.
2725 * @return {boolean} Whether the object looks like a DOM node.
2726 */
2727goog.dom.DomHelper.prototype.isNodeLike = goog.dom.isNodeLike;
2728
2729
2730/**
2731 * Whether the object looks like an Element.
2732 * @param {?} obj The object being tested for Element likeness.
2733 * @return {boolean} Whether the object looks like an Element.
2734 */
2735goog.dom.DomHelper.prototype.isElement = goog.dom.isElement;
2736
2737
2738/**
2739 * Returns true if the specified value is a Window object. This includes the
2740 * global window for HTML pages, and iframe windows.
2741 * @param {?} obj Variable to test.
2742 * @return {boolean} Whether the variable is a window.
2743 */
2744goog.dom.DomHelper.prototype.isWindow = goog.dom.isWindow;
2745
2746
2747/**
2748 * Returns an element's parent, if it's an Element.
2749 * @param {Element} element The DOM element.
2750 * @return {Element} The parent, or null if not an Element.
2751 */
2752goog.dom.DomHelper.prototype.getParentElement = goog.dom.getParentElement;
2753
2754
2755/**
2756 * Whether a node contains another node.
2757 * @param {Node} parent The node that should contain the other node.
2758 * @param {Node} descendant The node to test presence of.
2759 * @return {boolean} Whether the parent node contains the descendent node.
2760 */
2761goog.dom.DomHelper.prototype.contains = goog.dom.contains;
2762
2763
2764/**
2765 * Compares the document order of two nodes, returning 0 if they are the same
2766 * node, a negative number if node1 is before node2, and a positive number if
2767 * node2 is before node1. Note that we compare the order the tags appear in the
2768 * document so in the tree <b><i>text</i></b> the B node is considered to be
2769 * before the I node.
2770 *
2771 * @param {Node} node1 The first node to compare.
2772 * @param {Node} node2 The second node to compare.
2773 * @return {number} 0 if the nodes are the same node, a negative number if node1
2774 * is before node2, and a positive number if node2 is before node1.
2775 */
2776goog.dom.DomHelper.prototype.compareNodeOrder = goog.dom.compareNodeOrder;
2777
2778
2779/**
2780 * Find the deepest common ancestor of the given nodes.
2781 * @param {...Node} var_args The nodes to find a common ancestor of.
2782 * @return {Node} The common ancestor of the nodes, or null if there is none.
2783 * null will only be returned if two or more of the nodes are from different
2784 * documents.
2785 */
2786goog.dom.DomHelper.prototype.findCommonAncestor = goog.dom.findCommonAncestor;
2787
2788
2789/**
2790 * Returns the owner document for a node.
2791 * @param {Node} node The node to get the document for.
2792 * @return {!Document} The document owning the node.
2793 */
2794goog.dom.DomHelper.prototype.getOwnerDocument = goog.dom.getOwnerDocument;
2795
2796
2797/**
2798 * Cross browser function for getting the document element of an iframe.
2799 * @param {Element} iframe Iframe element.
2800 * @return {!Document} The frame content document.
2801 */
2802goog.dom.DomHelper.prototype.getFrameContentDocument =
2803 goog.dom.getFrameContentDocument;
2804
2805
2806/**
2807 * Cross browser function for getting the window of a frame or iframe.
2808 * @param {Element} frame Frame element.
2809 * @return {Window} The window associated with the given frame.
2810 */
2811goog.dom.DomHelper.prototype.getFrameContentWindow =
2812 goog.dom.getFrameContentWindow;
2813
2814
2815/**
2816 * Sets the text content of a node, with cross-browser support.
2817 * @param {Node} node The node to change the text content of.
2818 * @param {string|number} text The value that should replace the node's content.
2819 */
2820goog.dom.DomHelper.prototype.setTextContent = goog.dom.setTextContent;
2821
2822
2823/**
2824 * Gets the outerHTML of a node, which islike innerHTML, except that it
2825 * actually contains the HTML of the node itself.
2826 * @param {Element} element The element to get the HTML of.
2827 * @return {string} The outerHTML of the given element.
2828 */
2829goog.dom.DomHelper.prototype.getOuterHtml = goog.dom.getOuterHtml;
2830
2831
2832/**
2833 * Finds the first descendant node that matches the filter function. This does
2834 * a depth first search.
2835 * @param {Node} root The root of the tree to search.
2836 * @param {function(Node) : boolean} p The filter function.
2837 * @return {Node|undefined} The found node or undefined if none is found.
2838 */
2839goog.dom.DomHelper.prototype.findNode = goog.dom.findNode;
2840
2841
2842/**
2843 * Finds all the descendant nodes that matches the filter function. This does a
2844 * depth first search.
2845 * @param {Node} root The root of the tree to search.
2846 * @param {function(Node) : boolean} p The filter function.
2847 * @return {Array<Node>} The found nodes or an empty array if none are found.
2848 */
2849goog.dom.DomHelper.prototype.findNodes = goog.dom.findNodes;
2850
2851
2852/**
2853 * Returns true if the element has a tab index that allows it to receive
2854 * keyboard focus (tabIndex >= 0), false otherwise. Note that some elements
2855 * natively support keyboard focus, even if they have no tab index.
2856 * @param {!Element} element Element to check.
2857 * @return {boolean} Whether the element has a tab index that allows keyboard
2858 * focus.
2859 */
2860goog.dom.DomHelper.prototype.isFocusableTabIndex = goog.dom.isFocusableTabIndex;
2861
2862
2863/**
2864 * Enables or disables keyboard focus support on the element via its tab index.
2865 * Only elements for which {@link goog.dom.isFocusableTabIndex} returns true
2866 * (or elements that natively support keyboard focus, like form elements) can
2867 * receive keyboard focus. See http://go/tabindex for more info.
2868 * @param {Element} element Element whose tab index is to be changed.
2869 * @param {boolean} enable Whether to set or remove a tab index on the element
2870 * that supports keyboard focus.
2871 */
2872goog.dom.DomHelper.prototype.setFocusableTabIndex =
2873 goog.dom.setFocusableTabIndex;
2874
2875
2876/**
2877 * Returns true if the element can be focused, i.e. it has a tab index that
2878 * allows it to receive keyboard focus (tabIndex >= 0), or it is an element
2879 * that natively supports keyboard focus.
2880 * @param {!Element} element Element to check.
2881 * @return {boolean} Whether the element allows keyboard focus.
2882 */
2883goog.dom.DomHelper.prototype.isFocusable = goog.dom.isFocusable;
2884
2885
2886/**
2887 * Returns the text contents of the current node, without markup. New lines are
2888 * stripped and whitespace is collapsed, such that each character would be
2889 * visible.
2890 *
2891 * In browsers that support it, innerText is used. Other browsers attempt to
2892 * simulate it via node traversal. Line breaks are canonicalized in IE.
2893 *
2894 * @param {Node} node The node from which we are getting content.
2895 * @return {string} The text content.
2896 */
2897goog.dom.DomHelper.prototype.getTextContent = goog.dom.getTextContent;
2898
2899
2900/**
2901 * Returns the text length of the text contained in a node, without markup. This
2902 * is equivalent to the selection length if the node was selected, or the number
2903 * of cursor movements to traverse the node. Images & BRs take one space. New
2904 * lines are ignored.
2905 *
2906 * @param {Node} node The node whose text content length is being calculated.
2907 * @return {number} The length of {@code node}'s text content.
2908 */
2909goog.dom.DomHelper.prototype.getNodeTextLength = goog.dom.getNodeTextLength;
2910
2911
2912/**
2913 * Returns the text offset of a node relative to one of its ancestors. The text
2914 * length is the same as the length calculated by
2915 * {@code goog.dom.getNodeTextLength}.
2916 *
2917 * @param {Node} node The node whose offset is being calculated.
2918 * @param {Node=} opt_offsetParent Defaults to the node's owner document's body.
2919 * @return {number} The text offset.
2920 */
2921goog.dom.DomHelper.prototype.getNodeTextOffset = goog.dom.getNodeTextOffset;
2922
2923
2924/**
2925 * Returns the node at a given offset in a parent node. If an object is
2926 * provided for the optional third parameter, the node and the remainder of the
2927 * offset will stored as properties of this object.
2928 * @param {Node} parent The parent node.
2929 * @param {number} offset The offset into the parent node.
2930 * @param {Object=} opt_result Object to be used to store the return value. The
2931 * return value will be stored in the form {node: Node, remainder: number}
2932 * if this object is provided.
2933 * @return {Node} The node at the given offset.
2934 */
2935goog.dom.DomHelper.prototype.getNodeAtOffset = goog.dom.getNodeAtOffset;
2936
2937
2938/**
2939 * Returns true if the object is a {@code NodeList}. To qualify as a NodeList,
2940 * the object must have a numeric length property and an item function (which
2941 * has type 'string' on IE for some reason).
2942 * @param {Object} val Object to test.
2943 * @return {boolean} Whether the object is a NodeList.
2944 */
2945goog.dom.DomHelper.prototype.isNodeList = goog.dom.isNodeList;
2946
2947
2948/**
2949 * Walks up the DOM hierarchy returning the first ancestor that has the passed
2950 * tag name and/or class name. If the passed element matches the specified
2951 * criteria, the element itself is returned.
2952 * @param {Node} element The DOM node to start with.
2953 * @param {?(goog.dom.TagName|string)=} opt_tag The tag name to match (or
2954 * null/undefined to match only based on class name).
2955 * @param {?string=} opt_class The class name to match (or null/undefined to
2956 * match only based on tag name).
2957 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
2958 * dom.
2959 * @return {Element} The first ancestor that matches the passed criteria, or
2960 * null if no match is found.
2961 */
2962goog.dom.DomHelper.prototype.getAncestorByTagNameAndClass =
2963 goog.dom.getAncestorByTagNameAndClass;
2964
2965
2966/**
2967 * Walks up the DOM hierarchy returning the first ancestor that has the passed
2968 * class name. If the passed element matches the specified criteria, the
2969 * element itself is returned.
2970 * @param {Node} element The DOM node to start with.
2971 * @param {string} class The class name to match.
2972 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
2973 * dom.
2974 * @return {Element} The first ancestor that matches the passed criteria, or
2975 * null if none match.
2976 */
2977goog.dom.DomHelper.prototype.getAncestorByClass =
2978 goog.dom.getAncestorByClass;
2979
2980
2981/**
2982 * Walks up the DOM hierarchy returning the first ancestor that passes the
2983 * matcher function.
2984 * @param {Node} element The DOM node to start with.
2985 * @param {function(Node) : boolean} matcher A function that returns true if the
2986 * passed node matches the desired criteria.
2987 * @param {boolean=} opt_includeNode If true, the node itself is included in
2988 * the search (the first call to the matcher will pass startElement as
2989 * the node to test).
2990 * @param {number=} opt_maxSearchSteps Maximum number of levels to search up the
2991 * dom.
2992 * @return {Node} DOM node that matched the matcher, or null if there was
2993 * no match.
2994 */
2995goog.dom.DomHelper.prototype.getAncestor = goog.dom.getAncestor;