Getting the class attribute of an element in GWT

Spent a while on solving this one…

For the new version of my GWT application, I needed to get the class attribute of an element.
This code was working fine in Firefox:

    HTML html = new HTML(text);
    NodeList links = html.getElement().getElementsByTagName(”a”);
    for (int i = 0; i < links.getLength(); i++) {
      com.google.gwt.user.client.Element link =
        (com.google.gwt.user.client.Element) links.getItem(i);

      Log.info(link.getAttribute("class"));
    }

However, when I started testing other browsers this appeared not to work in Internet Explorer.
So I started trying some alternatives:

      Log.info(DOM.getElementAttribute(link, "class"));
      // Chrome & FF: ok   IE: ""

      Log.info( DOM.getElementProperty(link, "class"));
      //Chrome, FF& IE: null

      Log.info(link.getAttribute("class"));
      //Chrome & FF: ok   IE: ""

      Log.info(getAttribute(link, "class"));
      //Chrome & FF: ok   IE: null

      Log.info(link.getClassName());
      //Chrome, FF & IE: ok 
    }

    public static native String getAttribute(Element elem, String attr)
    /*-{
       return elem.getAttribute(attr);
    }-*/; 

At last link.getClassName() did the trick, but it took me some time before I realized that class is treated as an exceptional attribute in IE and that this method did exist at all!

Would be nice if there was a mechanism (assert?) that pointed to this method when getAttribute is called with class (and what about id?). But for now I hope google is your friend when you stumble on this issue…

3 Responses to “Getting the class attribute of an element in GWT”

  1. Eggsy Says:

    Hi there

    Many thanks for this. I went through the same testing methods as well.

    Unusually on the GWT API docs it seems to point at using the DOM.getElementProperty methods but they don’t seem to resolve do they which is annoying!

    Seems GWT might need to update their docs?!

  2. Eggsy Says:

    Also just to let you know the getClassName() method also works on the Safari browser.

  3. int getclassname Says:

    […] while(1){ if(!::GetClassName(hwnd, szName, _countof(szName)))break; if(wcsicmp …Blok blogs Getting the class attribute of an element in GWTAt last link.getClassName() did the trick, but it took me some time before I realized that class is […]

Leave a Reply

©2006 - 2010 Rintcius Blok