Google Web Toolkit (GWT): Casting an Element retrieved with DOM.getElementById()
Google Web Toolkit is just great! Being able to use Eclipse in order to develop an Ajax application for many (including me) is already argument enough. While I am not really into strong typing, for me as a mainly PHP and JavaScript programmer, sometimes it is still good to be reminded that strong typing exists. Let's have a look at an interesting thing that can happen in an Ajax app written with GWT, assuming that we wanted to retrieve a checkbox input element:
Element checkbox = DOM.getElementById("someId");
In JavaScript this looks like this:var checkbox = document.getElementById("someId");
Notice the small difference? In Java we are forced to give the checkbox a type, in JavaScript we just take whatever comes back. But what if you know that the Element actually is a checkbox? In this case you need to cast the Element to an InputElement:InputElement checkbox = DOM.getElementById("someId").cast();
It took me some time to figure this out, so I thought I'd share this with others. Maybe the solution was too obvious, anyway, suddenly the InputElement becomes something useful you can work with, e.g. check the isChecked() method:InputElement checkbox = DOM.getElementById("someId").cast();
if (!checkbox.isChecked()) {
??checkbox.setChecked(true);
}
if (!checkbox.isChecked()) {
??checkbox.setChecked(true);
}
If you are looking for a good GWT book, I found GWT in Action: Easy Ajax with the Google Web Toolkit relatively helpful when I started with my first GWT applications.
Image from amazon.de