gitweb.js: Provide getElementsByClassName method (if it not exists)

The code is simplified and does not support full specification of native getElementsByClassName method, but implements just subset that would be enough for gitweb, supporting only single class name. Signed-off-by: John 'Warthog9' Hawley <warthog9@eaglescrag.net> Signed-off-by: Jakub Narebski <jnareb@gmail.com> Signed-off-by: Junio C Hamano <gitster@pobox.com>

Jakub Narebski committed Apr 28, 2011 at 21:04 UTC 1cae3ee70dd9e389a83c494fbc95aa63c01128a1
1 file changed +51
gitweb/static/js/lib/common-lib.js
+51
@@ -88,6 +88,57 @@ function createRequestObject() {
88 }
89
90
91 +/* ............................................................ */
92 +/* Support for legacy browsers */
93 +
94 +/**
95 + * Provides getElementsByClassName method, if there is no native
96 + * implementation of this method.
97 + *
98 + * NOTE that there are limits and differences compared to native
99 + * getElementsByClassName as defined by e.g.:
100 + * https://developer.mozilla.org/en/DOM/document.getElementsByClassName
101 + * http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-getelementsbyclassname
102 + * http://www.whatwg.org/specs/web-apps/current-work/multipage/dom.html#dom-document-getelementsbyclassname
103 + *
104 + * Namely, this implementation supports only single class name as
105 + * argument and not set of space-separated tokens representing classes,
106 + * it returns Array of nodes rather than live NodeList, and has
107 + * additional optional argument where you can limit search to given tags
108 + * (via getElementsByTagName).
109 + *
110 + * Based on
111 + * http://code.google.com/p/getelementsbyclassname/
112 + * http://www.dustindiaz.com/getelementsbyclass/
113 + * http://stackoverflow.com/questions/1818865/do-we-have-getelementsbyclassname-in-javascript
114 + *
115 + * See also http://ejohn.org/blog/getelementsbyclassname-speed-comparison/
116 + *
117 + * @param {String} class: name of _single_ class to find
118 + * @param {String} [taghint] limit search to given tags
119 + * @returns {Node[]} array of matching elements
120 + */
121 +if (!('getElementsByClassName' in document)) {
122 + document.getElementsByClassName = function (classname, taghint) {
123 + taghint = taghint || "*";
124 + var elements = (taghint === "*" && document.all) ?
125 + document.all :
126 + document.getElementsByTagName(taghint);
127 + var pattern = new RegExp("(^|\\s)" + classname + "(\\s|$)");
128 + var matches= [];
129 + for (var i = 0, j = 0, n = elements.length; i < n; i++) {
130 + var el= elements[i];
131 + if (el.className && pattern.test(el.className)) {
132 + // matches.push(el);
133 + matches[j] = el;
134 + j++;
135 + }
136 + }
137 + return matches;
138 + };
139 +} // end if
140 +
141 +
142 /* ............................................................ */
143 /* unquoting/unescaping filenames */
144