Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 324
Michael Kay Avatar asked Feb 26 '11 10:02

Michael Kay


People also ask

How can we fetch all attributes for an HTML element?

To get all of the attributes of a DOM element: Use the getAttributeNames() method to get an array of the element's attribute names. Use the reduce() method to iterate over the array. On each iteration, add a new key/value pair containing the name and value of the attribute.

What are DOM attributes?

The attributes property in HTML DOM returns the group of node attributes specified by NamedNodeMap objects. The NamedNodeMap object represents the collection of attribute objects and can be accessed by index number. The index number starts at 0. Syntax: node.attributes.

How do I know if a element is DOM?

Use the getElementsByTagName to Check the Existence of an Element in DOM. The function getElementsByTagName() can return all elements with the specified tagName in DOM . The return of the function can be one or more elements or null if no element is found.

What are attributes in JavaScript?

The attributes are special words used inside the start tag of an HTML element to control the tag's behavior or provides additional information about the tag. JavaScript provides several methods for adding, removing or changing an HTML element's attribute.


1 Answers

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();
    ...
}
like image 198
Chris Lercher Avatar answered Oct 17 '22 14:10

Chris Lercher