dom.js 109 KB

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