I have the following function that is supposed to get all elements in a document with the given class:
function getElementByClass(objClass)
{
// This function is similar to 'getElementByID' since there is no inherent function to get an element by it's class
var elements = (ie) ? document.all : document.getElementsByTagName('*');
for (i=0; i<elements.length; i++)
{
alert(elements[i].className);
alert(objClass);
if (elements[i].className==objClass)
{
return elements[i]
}
}
}
When I call this function with:
<script type="text/javascript">document.write(getElementByClass('done'));</script>
Nothing happens. Is there something wrong with the function?
This function does not get all elements with that class name, it gets one. And what is your intent with the way you are calling it?
document.writeseems like a funny thing to do with a DOM element already on your page.I hate to just say “use jquery”… but you probably should.
Aside from the missing declaration of
ie, this function does work. One problem you will have with it is if you have multiple classes on an element, this function won’t work.