Issue
I am able to get an element by Id like this in JavaFX.
Element nameField = engine.getDocument().getElementById( "name" );
How do I do the same given element's classname?
Thanks.
Solution
I came across this and saw there wasn't much for answers. The way I found way to work with dom classes is not great but it gets the job done.
To add a class on a Node you obtained, use the setAttribute()
method. Be careful to maintain any classes that might already exist on the Node
.
Document doc = engine.getDocument();
if (doc != null){
Element elem = doc.getElementById('someID');
String classNames = elem.getAttribute("class");
classNames += " someClass"; //note the whitespace!
elem.setAttribute("class", classNames);
}
Then, if you wish to search the DOM by class you can execute javascript to do so using the executeScript
on the WebEngine
. The return type depends on what you're asking the script to do.
Small note: disabling javascript via engine.setJavaScriptEnabled(false);
does not prohibit use of the engine.executeScript()
method.
HTMLCollection result = (HTMLCollection)engine.executeScript("document.getElementsByClassName('someClass')");
However inefficient, I did this to determine what I would be getting back from executeScript()
before writing any further code:
Object result = engine.executeScript("document.getElementsByClassName('someClass')");
System.out.println(result.getClass().getName());
Like I said it isn't great, but you can write some wrapper functions to make it easier to work with. Hope this helps!
Answered By - Lucas
Answer Checked By - Mary Flores (JavaFixing Volunteer)