External Libraries

Jsoup Iterate all elements of HTML example

Jsoup Iterate all elements of HTML example shows how to select and iterate all elements of HTML document using Jsoup. Example also shows how to iterate elements of HTML body.

How to iterate all elements of HTML using Jsoup?

Jsoup provides select method which accepts CSS style selectors to select the elements. For selecting all the elements of HTML page, you need to pass “*” as the selector as given below.

“*” selector selects all the elements of the HTML document. You can then iterate over elements using for loop as given below.

Output

As you can see from the output, when we print text of an element, it prints text contained in all the child elements as well.

If you want all elements of the HTML body only, you can use selector like,

Output

If you want only direct children of the body tag, you can use children method as given below.

Output

As you can see from the output, <strong> element was not returned because it is not a direct child of the body tag.

Please let us know your views in the comments section below.

Tags
Join 1000+ fellow learners! Enter your email address below: