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.

Want to learn quickly?
Try one of the many quizzes. I promise you will not be disappointed.

Tags

About the author

rahimv

rahimv

rahimv has over 15 years of experience in designing and developing Java applications. His areas of expertise are J2EE and eCommerce. If you like the website, follow him on Facebook, Twitter or Google Plus.

2 Comments

Your email address will not be published. Required fields are marked *