»
EnglishFrenchVietnamese

Print - getElementsByClassName Deluxe Edition - JavaScriptBank.com

Full version: jsB@nk » Snippet » getElementsByClassName Deluxe Edition
URL: https://www.javascriptbank.com/getelementsbyclassname-deluxe-edition.html

getElementsByClassName Deluxe Edition © JavaScriptBank.comJavaScript language does not provide us a function for obtaining elements by class, only by id, name, and tag name. This JavaScript snippet will accomplish that, and includes optional arguments with defaults and support for multiple classnames in any order. It works in Internet Explorer, Firefox, Opera, Safari and Mac.

Full version: jsB@nk » Snippet » getElementsByClassName Deluxe Edition
URL: https://www.javascriptbank.com/getelementsbyclassname-deluxe-edition.html



JavaScript
<script type="text/javascript">// Created by: Stuart Colville | http://muffinresearch.co.uk/function getElementsByClassName(strClass, strTag, objContElm) {  strTag = strTag || "*";  objContElm = objContElm || document;  var objColl = objContElm.getElementsByTagName(strTag);  if (!objColl.length &&  strTag == "*" &&  objContElm.all) objColl = objContElm.all;  var arr = new Array();  var delim = strClass.indexOf('|') != -1  ? '|' : ' ';  var arrClass = strClass.split(delim);  for (var i = 0, j = objColl.length; i < j; i++) {    var arrObjClass = objColl[i].className.split(' ');    if (delim == ' ' && arrClass.length > arrObjClass.length) continue;    var c = 0;    comparisonLoop:    for (var k = 0, l = arrObjClass.length; k < l; k++) {      for (var m = 0, n = arrClass.length; m < n; m++) {        if (arrClass[m] == arrObjClass[k]) c++;        if (( delim == '|' && c == 1) || (delim == ' ' && c == arrClass.length)) {          arr.push(objColl[i]);          break comparisonLoop;        }      }    }  }  return arr;}// To cover IE 5.0's lack of the push methodArray.prototype.push = function(value) {  this[this.length] = value;}</script>