Skip to content
Advertisement

In GWT, How can I get all attributes of an element in the HTML DOM?

I can’t see any method on the com.google.gwt.dom.client.Element class that allows me to get all attributes of an element node. Have I missed anything?

Presumably I can get the attributes array of the underlying Javascript object by dropping into native code? I know the results are browser-dependent, but there seem to be known workarounds for that. I haven’t dived much into native JS, so if someone can show me how to do it, that would be a bonus.

Advertisement

Answer

I looked for a convenience method in GWT, but was surprised that I couldn’t find one.

Presumably I can get the attributes array of the underlying Javascript object by dropping into native code? I know the results are browser-dependent, …

Yes, with JSNI, you can define a method that returns the element’s “attributes” property as a suitable Java object:

public static native JsArray<Node> getAttributes(Element elem) /*-{
   return elem.attributes;
}-*/;

You can use it like this:

final JsArray<Node> attributes = getAttributes(element);
for (int i = 0; i < attributes.length(); i ++) {
    final Node node = attributes.get(i);
    String attributeName = node.getNodeName();
    String attributeValue = node.getNodeValue();
    ...
}
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement