Find an element by CSS selector in GWT

后端 未结 5 1847
不思量自难忘°
不思量自难忘° 2021-01-11 09:21

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 a

5条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-11 09:45

    Here's an example using the GWT Element and Node classes to find a single nested element with a given class name. This is not as open ended and powerful as a literal CSS selector, but can be modified as needed for your specific use case:

    static public Element findFirstChildElementByClassName( Widget w, String className ){
        return findFirstChildElementByClassName( w.getElement(), className );
    }
    static private Element findFirstChildElementByClassName( Element e, String className ){     
        for( int i=0; i != e.getChildCount(); ++i ){
            Node childNode = e.getChild(i);
            if( childNode.getNodeType() == Node.ELEMENT_NODE ){
                Element childElement = (Element)childNode;
                if( childElement.getClassName().equalsIgnoreCase( className ) )
                    return childElement;
                else if( childElement.hasChildNodes() ){
                    Element grandChildElement = 
                        findFirstChildElementByClassName( 
                                childElement, className );
                    if( grandChildElement != null ) return grandChildElement;
                }
            }
        }
        return null;
    }
    

提交回复
热议问题