Go to content Go to menu

getElementsByTagAndClass

Thu Aug 3, 13:20

This is a nice little utility function that I want to save.

getElementsByTagAndClass(document, 'div', 'product') will return an Array of div elements with class name exactly equal to "product".

function getElementsByTagAndClass(root_element, tag, className) {
  var tags_with_class = new Array()
  
  var tags = root_element.getElementsByTagName(tag)
  
  for (var i=0; i<tags.length; i++)
    if (tags[i].className == className)
      tags_with_class.push(tags[i])
      
  return tags_with_class
}

Enjoy.

Caveat: this may not work in IE. I'm not sure if IE supports someElement.getElementsByTagName(..) when someElement is not document.