We Recommend

Pro JavaScript Techniques Pro JavaScript Techniques
Pro JavaScript Techniques is the ultimate JavaScript book for the modern web developer. It provides everything you need to know about modern JavaScript, and shows what JavaScript can do for your web sites. This book doesn't waste any time looking at things you already know, like basic syntax and structures.


Posted By

travis on 06/29/06


Tagged

javascript class GetElementsByClassName node


Versions (?)


Who likes this?

63 people have marked this snippet as a favorite


tylerhall
bomberstudios
luman
xaviaracil
luxuryluke
designerd
mhinze
speck
Zikes
jonbaer
kgosser
rengber
hxseven
mbadran
ttscoff
visualAesthetic
maese
dividespace
Hollow
hkmd
lhplam
dmarten
eunjoo1984
noname
jacksont123
miyazima
nankoweap
Phoenix
willbolton
n00ge
spiralfunk
manub
georgeantoniadis
rich13
heinz1959
j_junyent
SamuelMiller
eskey
benrasmusen
Winkyboy
glex
celoria
adix
willgarrison
SpinZ
vasya1905
marcio
neoprolog
johnself
Wizzle
lukaszkorecki
Baris
mb
paullorentzen
kevcow
JustinCrossman
shii
aristoworks
matpol
jamesming
chinlin62
esquareda


GetElementsByClassName()


Published in: JavaScript 


From here: http://www.dustindiaz.com/top-ten-javascript/

  1. function getElementsByClassName(searchClass, node, tag)
  2. {
  3. var classElements = new Array();
  4. if (node == null)
  5. {
  6. node = document;
  7. }
  8. if (tag == null)
  9. {
  10. tag = '*';
  11. }
  12. var els = node.getElementsByTagName(tag);
  13. var elsLen = els.length;
  14. var pattern = new RegExp("(^|\\s)" + searchClass + "(\\s|$)");
  15. for (var i = 0, j = 0; i < elsLen; i++)
  16. {
  17. if (pattern.test(els[i].className))
  18. {
  19. classElements[j] = els[i];
  20. j++;
  21. }
  22. }
  23. return classElements;
  24. }

Report this snippet 

Comments

RSS Icon Subscribe to comments
Posted By: brito on January 24, 2008
function getElementsByClassName(searchClass, node, tag){
  var classElements=[];
  node = node || document;
  var pattern = new RegExp('(^|\\s)' + searchClass+ '(\\s|$)');
  var els = (!tag &&  node.all) || node.getElementsByTagName(tag|| '*');
  var elsLen = els.length;
  for(var i=0, j=0;i<els.length;i++){
    if(pattern.test(els[i].className)){
      classElements[j] = els[i];
      j++;
    }
  }
  return classElements;
}
Posted By: sosof on February 18, 2008

function getElementsByClassName(searchClass, node, tag){ var classElements=[]; node = node || document; var pattern = new RegExp('(^|\s)' + searchClass+ '(\s|$)'); var els = (!tag && node.all) || node.getElementsByTagName(tag|| '*'); var elsLen = els.length; for(var i=0, j=0;i

You need to login to post a comment.