Regex Rookie
Regex Rookie

Reputation: 10662

Jsoup Select only innermost divs

Is there a way to select only innermost divs (i.e. divs that do not contain other divs) in Jsoup?

To clarify: I am referring to divs only. That is, if a div contains elements that aren't divs but it doesn't contain any div, it is considered (for my case) an "innermost div".

Upvotes: 3

Views: 749

Answers (2)

Jonathan Hedley
Jonathan Hedley

Reputation: 10522

You can use a selector like div:not(:has(div)) -- i.e. "find divs that do not contain divs".

Elements innerMostDivs = doc.select("div:not(:has(div))");

Upvotes: 1

BalusC
BalusC

Reputation: 1108712

Jsoup works with CSS selectors. But what you want is not possible with a CSS selector. So this is out of question. You'd need to examine every single div in a loop.

Elements divs = document.select("div");
Elements innerMostDivs = new Elements();

for (Element div : divs) {
    if (div.select(">div").isEmpty()) {
        innerMostDivs.add(div);
    }
}

// ...

Upvotes: 3

Related Questions