Get all elements of particular type and class without jQuery

I wanted some nice function, that will return all DOM elements:

  • of given element type (name),
  • contained in another element,
  • having given class.

For example, to get all list items (<li>) with some class, but inside <ol> rather than in entire DOM tree.

I failed to find one of such, so I wrote it.

Here is the code. This function will seek all child elements (all child nodes) of elementType type, contained in rootElement, but return only these, that has className class.

[code language=”javascript”]
var getElementsByClassName = function (rootElement, elementType, className)
{
var arrElements = (elementType == "*" && rootElement.all)? rootElement.all : rootElement.getElementsByTagName(elementType);
var arrReturnElements = new Array();

className = className.replace(/-/g, "\-");

var oRegExp = new RegExp("(^|\s)" + className + "(\s|$)");
var oElement;

for(var i=0; i<arrElements.length; i++)
{
oElement = arrElements[i];
if(oRegExp.test(oElement.className))
{
arrReturnElements.push(oElement);
}
}

return (arrReturnElements)
}
[/code]

This task is more then easy (obvious?) with jQuery. But for people/projects that doesn’t use jQuery, this function may be handy.

Leave a Reply