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