Search code examples
javajsoup

Get the span with content using Jsoup


I have this html

<span style="font-size:20px">
    <span style="font-family:verdana">Text 1</span>
</span>
<span style="font-size:11px">
    <span style="fontfamily:arial">Text 2</span>
</span>

I want to get span elements that have content

<span style="fontfamily:arial">Text 2</span>
<span style="font-family:verdana">Text 1</span>

I'm using JSoup and here are my tries

doc.select("span[text!=\"\"]")
doc.select("span[text]")
doc.select("span[content]")
doc.getElementsByTag("span").stream().filter(p -> p.hasText())

Coul anyone helps me?

Thanks in advance


Solution

  • Actually, if you want to select spans which should have text between that span, you may easily filter all the spans by using: Element.ownText​() is not empty. See: https://jsoup.org/apidocs/org/jsoup/nodes/Element.html#ownText-- public String ownText​() Gets the text owned by this element only; does not get the combined text of all children.