Reputation: 1389
I am looking for ways to grab an element by name. I tried iterating one element at a time by using Element.getAttributes.getAttributeNames()
and iterated through each element to find the name then checked it with the name I am looking for. Any alternatives or optimized way to grab the element directly?
Upvotes: 2
Views: 1635
Reputation: 7494
This is the method I use to retrieve elements by tag name. For mixed-content
elements (e.g., sub
, sup
, b
, i
), you need to look in the attributes of the “fake” content
elements.
/**
* Returns all elements of a particular tag name.
*
* @param tagName The tag name of the elements to return (e.g., HTML.Tag.DIV).
* @param document The HTML document to find tags in.
* @return The set of all elements in the HTML document having the specified tag name.
*/
public static Element[] getElementsByTagName(HTML.Tag tagName, HTMLDocument document)
{
List<Element> elements = new ArrayList<Element>();
for (ElementIterator iterator = new ElementIterator(document); iterator.next() != null;)
{
Element currentEl = iterator.current();
AttributeSet attributes = currentEl.getAttributes();
HTML.Tag currentTagName = (HTML.Tag) attributes.getAttribute(StyleConstants.NameAttribute);
if (currentTagName == tagName)
{
elements.add(iterator.current());
} else if (currentTagName == HTML.Tag.CONTENT) {
for (Enumeration<?> e = attributes.getAttributeNames(); e.hasMoreElements();)
{
if (tagName == e.nextElement())
{
elements.add(iterator.current());
break;
}
}
}
}
return elements.toArray(new Element[0]);
}
Upvotes: 1
Reputation: 2010
I am looking for ways to grab an element by name.
Perhaps you could use the getElement()
method? It takes as an argument the String value for the id of the element you are searching for.
Upvotes: 0