Javascript DOM - getElementsByClassName


/ Published in: JavaScript
Save to your folder(s)

Similar to [Get Elements by Class Name]( http://snipplr.com/view/1696/get-elements-by-class-name/), but with optional "tag" parameter. Performance is increased by first retrieving the desired tag if available.


Copy this code and paste it in your HTML
  1. getElementsByClassName: function(classname, baseNode, tag) {
  2. baseNode = baseNode || document.getElementsByTagName("body")[0];
  3. var a = [];
  4. var re = new RegExp('\\b' + classname + '\\b');
  5. var els = baseNode.getElementsByTagName(tag || "*");
  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

You need to login to post a comment.