I'm trying to grab an arbitrary element using a CSS selector (eg. "#someId .className a") in GWT.
I'm building a JS widget that can live on a 3rd party website and want to be able to interact with elements on the page. Searching through the JavaDocs I don't see anything that can find an element by selector. I did come across GQuery, but it seems like the project might be dead and I'm not sure if it works with GWT 2.
One option I've considered is wrapping an existing library (jQuery, Mootools, Prototype, etc) into a GWT class and exposing the desired behavior through JSNI. It seems this might be very builky.
Anyone have experience using generic CSS selectors in GWT?
To search for nodes by their CSS selectors, use the shortcut: CMD / Ctrl + F. This means you can search for .
The querySelector() method is available on the document object or any Element object. The querySelectorAll() method returns a static NodeList of elements that match the CSS selector. If no element matches, it returns an empty NodeList .
There's the DOM
class, that provides many wrapper methods for accessing the DOM tree. There's no function that takes a CSS selector jQuery style that I'm aware of - GWT just encourages/enforces accessing DOM elements through Widgets (and such), not directly - though I understand that in your case such "low-level" approach might be needed. The only way I see pulling that off through pure Java GWT methods is via lots and lots of (probably horrible) chaining/invocations of the DOM
class. It'd be easier if all you had to do was access some id
- for that there's RootPanel.get(id)
(and DOM.getElementById(id)
, they differ in what type of objects they return).
However, like you already suggested, JSNI might offer a better solution - try returning, for example, $wnd.$("#someId .className a")
from JSNI as an Element
- actually, you can return anything as anything from JSNI, GWT will just crap up the second you try to use, say an int as a DOM element or something.
PS: while the GQuery project does seem dead/inactive, it might be worth checking how they wrapped the jQuery calls (such as $
) so that they could be used seemingly in GWT.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With