Jsoup Iterate all elements of HTML example

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

How to iterate all elements of HTML using Jsoup?

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

The “*” 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 the 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 the 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, the “<strong>” element was not returned because it is not a direct child of the HTML body tag.

This example is a part of the Jsoup tutorial with examples.

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

About the author

RahimV

RahimV

My name is RahimV and I have over 16 years of experience in designing and developing Java applications. Over the years I have worked with many fortune 500 companies as an eCommerce Architect. My goal is to provide high quality but simple to understand Java tutorials and examples for free. If you like my website, follow me on Facebook and Twitter.

2 Comments

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

Online Shopping