Skip to content

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.

Please also visit how to remove HTML tags from a string using Jsoup in Java.

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

2 comments

Leave a Reply

Your email address will not be published.