Posted By

tylerhall on 11/20/06


Tagged

javascript class name


Versions (?)

Who likes this?

9 people have marked this snippet as a favorite

janetmck
vali29
hr1v
jasonseney
gabrielu
guo3823538
bindzus
o0110o
vbmike


Get Elements By Class Name


 / Published in: JavaScript
 

Returns a list of child nodes with the supplied class name.

  1. function getElementsByClassName(classname, node) {
  2. if(!node) node = document.getElementsByTagName("body")[0];
  3. var a = [];
  4. var re = new RegExp('\\b' + classname + '\\b');
  5. var els = node.getElementsByTagName("*");
  6. for(var i=0,j=els.length; i<j; i++)
  7. if(re.test(els[i].className))a.push(els[i]);
  8. return a;
  9. }

Report this snippet  

Comments

RSS Icon Subscribe to comments
Posted By: mountainash on December 21, 2009

Can be expanded to the following if your server doesn't handle carriage returns well:

function getElementsByClassName(classname, node) { if (!node) { node = document.getElementsByTagName('body')[0]; } var a = [], re = new RegExp('\\b' + classname + '\\b'); els = node.getElementsByTagName('*'); for (var i = 0, j = els.length; i < j; i++) { if ( re.test(els[i].className) ) { a.push(els[i]); } } return a; }

You need to login to post a comment.