mica
mica

Reputation: 4308

Can I define an ID for an HTMLPanel?

How can I define the ID for an HTMLPanel? Of course I could surround the HTML with a <div id="anID"> but this would also not set the ID of the panel.

Upvotes: 2

Views: 2058

Answers (2)

Chris Lercher
Chris Lercher

Reputation: 37778

htmlPanel.getElement().setId("myId");

If the panel is defined in a UiBinder template, then you'll have to make it accessible in the Java class via "ui:field":

<g:HTMLPanel ui:field="htmlPanel">...</g:HTMLPanel>
...

@UiField
HTMLPanel htmlPanel;

public MyWidget() {
    initWidget(uiBinder.createAndBindUi(this));
    htmlPanel.getElement().setId("myId");
}

Note: Using <g:HTMLPanel id="myId"> does not work.

There's a reason, why using ids wasn't made simpler for GWT widgets:

You must be very careful not to have the same id twice on the same page. This happens especially easily with widgets, because of the natural re-use factor. (Not only may the widget be re-used, but maybe also the parent widget...)

So e.g. if MyWidget can appear multiple times at the same time in your page document, you'll have to make sure to set a different id each time. It is possible to do that, and if you want, you can use com.google.gwt.dom.client.Document.createUniqueId().

Or, if possible, maybe use a CSS class instead of an id (because css classes can and should be re-used on the same page).

Upvotes: 6

Nicolas Morel
Nicolas Morel

Reputation: 315

You can do it like that :

htmlPanel.getElement().setId( "yourId" );

This works for any widget/element.

Upvotes: 5

Related Questions