JS according to the class name to locate objects, getElementsByClassName

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
 <head>
  <title>According to the class object search</title>
  <script type="text/javascript">
		function getElementsByClassName(a, b) {
			if (a.getElementsByClassName) {
				return a.getElementsByClassName(b);
			} else {
				return function c(m, k) {
					if (k == null) {
						k = document;
					}
					var h = [], g = k.getElementsByTagName("INPUT"), d = g.length, l = new RegExp("(^|\\s)" + m + "(\\s|$)"), f, e;
					for (f = 0, e = 0; f <d; f++) {
						if (l.test(g[f].className)) {
							h[e] = g[f];
							e++;
						}
					}
					return h;
				}(b, a);
			}
		}

		function view(){
			var v = getElementsByClassName(document,"a");
			alert(v.length);
			alert(v[1].id);
		}
  </script>
 </head>

 <body>
  
<div class="a" id=1  style="width:300px;height:300px;background:red;float:left">

</div>
<div class="a" id=2 style="width:300px;height:300px;background:green;float:left">

</div>
<div class="a" id=3 style="width:300px;height:300px;background:red;float:left">

</div>

<input type="button" value="See classname for a number of a" onclick="view()"/>
 </body>
</html>

Posted by Leonard at December 19, 2013 - 5:32 AM