ploosh
ploosh

Reputation: 115

using document.getElementsByTagName doesn't find elements added dynamically (IE6)

I am trying to write a method that grabs all the elements of a certain classname for browsers that don't have the 'getElementsByClassName' method. This works perfectly for elements that are generated server-side, however the page has the ability to add elements dynamically for some reason 'window.document.all' does not get these dynamic elements. Any ideas? Method below.

function getClassName(class) {
        var i, neededStuff = [], elements = document.getElementsByTagName('*');

        for (i = 0; i < elements.length; i++) {
            if (elements[i].className == class) {
                neededStuff[neededStuff.length] = elements[i];
            }
        }
        return neededStuff;
    }

Upvotes: 2

Views: 1605

Answers (2)

meder omuraliev
meder omuraliev

Reputation: 186562

class is a reserved keyword in IE. Don't use it literally. Change class to something like theClass.

Also, try document.getElementsByTagName('*') instead of document.all if changing class doesn't do it.

EDIT:

http://work.arounds.org/sandbox/72

Works perfectly for me in IE6 ^

Let me try dynamically adding...

EDIT #2: works fine..

http://work.arounds.org/sandbox/72

Upvotes: 4

turtlepick
turtlepick

Reputation: 2714

Use jQuery :)

http://jquery.com/

$('.ClassName') 

will return your elements :)

then you can change it's value, add classes very easily!

Some great tutorials here

http://docs.jquery.com/Tutorials

Upvotes: 1

Related Questions