Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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".

like image 260
Regex Rookie Avatar asked Mar 15 '26 17:03

Regex Rookie


2 Answers

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);
    }
}

// ...
like image 81
BalusC Avatar answered Mar 17 '26 05:03

BalusC


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))");
like image 33
Jonathan Hedley Avatar answered Mar 17 '26 06:03

Jonathan Hedley



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!