Search code examples
javahtmlgwt

How to Access DOM inside HTML object in GWT


How can I access DOM inside an HTML object which is fetched via RequestBuilder? Following is a shortened code regarding my question:

RequestBuilder requestBuilder = new RequestBuilder(
    RequestBuilder.POST, 
    "/experiment.txt");

requestBuilder.setCallback(new RequestCallback() {
    public void onResponseReceived(Request request, Response response) {
        if (200 == response.getStatusCode()) {
            HTML responseHTML = new HTML(response.getText());
            //TODO parse responseHTML
        } 
    }

    public void onError(Request request, Throwable exception) {}
});

Suppose that, following is the contents of responseHTML:

HTML responseHTML=new HTML(
    "<div id='div_1'>my div 1</div>" + 
    "<div id='div_2'>my div 2</div>");

Is it possible to get div_1 from inside responseHTML in such a way like:

responseHTML.getElementById("div_1");

Solution

  • After you attach your responseHTML to the DOM, you can use Dom.getElementById(String id)

    If you haven't attached the responseHTML to the DOM, you can try to use the GQuery framework to select/find needed DOM elements. Simple example would be:

    // select div with id=div_1 from responseLabel element
    GQuery divWithIdQuery = GQuery.$("div#div_1", responseLabel);
    
    // assuming that only one div was selected you can get its content :
    String div1HTML = divWithIdQuery.toString();
    
    // You can get the Element as well
    Element div1Element = divWithIdQuery.get(0);