Question

I'm iterating through a list of elements using jsoup, but periodically need to find one element that doesn't occur directly after the current element.

For example, if I'm iterating through and come to an img tag, I want to find the very next a tag occurring after that img tag. But, there could be a few tags in between the two.

Here's some example code:

for (Element e : elements) {
    if (e.tagName().equalsIgnoreCase("img")) {
        // Do some stuff with "img" tag
        // Now, find the next tag in the list with tag <a>
    }

    // Do some other things before the next loop iteration
}

I thought something like e.select("img ~ a") should work, but it returns no results.

What's a good way of doing this in jsoup?

Was it helpful?

Solution

This appears to be a way of accomplishing the stated goal. Not sure it's the most efficient, but it is the most straightforward.

Element node = e.nextElementSibling();
while (node != null && !node.tagName().equalsIgnoreCase("a")) {
    node = node.nextElementSibling();
}

I was hoping for a way to run the equivalent of e.nextElementSibling("a"). Perhaps something for me to contribute back to jsoup ;-)

OTHER TIPS

Use the nextElementSibling() method.

Inside your if statement add the following code:

Element imgNext = e.nextElementSibling();
do {
    Element a = imgNext.select("a[href]").first();         
} while (imgNext!=null && a==null);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top