Reputation: 3364
I'm using the Java Scripting API which is working quite well. Now I have a function where I want to get all <a>
tags from a String and then add/remove attributes before returning the manipulated String. The problem of course is, that I can't just use document.getElementsByTagName
. Is there any easy option that comes to your mind without going through regex-hell?
Please note that I'm currently running on Java 7 (with Rhino), planning to update to Java 8 (with Nashorn), so I don't want to use any Rhino specific APIs.
Upvotes: 0
Views: 458
Reputation: 11
In the book "Learning JavaScript Design Patterns" by Addi Osmani, author mentions 3 alternatives to a similar problem, obviously being getElementById() the fastest.
Excerpt from book:
Imagine that we have a script where for each DOM element found on page with class "foo," we wish to increment a counter. What's the most efficient way to query for this collection of elements? Well, there are a few different ways this problem could be tackled:
- Select all of the elements in the page and then store references to them. Next, filter this collection and use regular expressions (or another means) to store only those with the class "foo."
- Use a modern native browser feature such as
querySelectorForAll()
to select all of the elements with the class "foo."- Use a netive feature such as
getElementsByClassName()
to similarly...
Another way is, since you're using Nashorn/Rhino, you could use the Java implementation of the Xerces library to manipulate the DOM.
Hope this helps you find out the solution.
Upvotes: 1