jsoup Get All HTML Elements in Java

Tags: jsoup HTML Parser

In this post, we are going to learn how to use jsoup Java library to find all HTML elements in a HTML document.

Add jsoup library to your Java project

To use jsoup Java library in the Gradle build project, add the following dependency into the build.gradle file.

compile 'org.jsoup:jsoup:1.13.1'

To use jsoup Java library in the Maven build project, add the following dependency into the pom.xml file.

<dependency>
    <groupId>org.jsoup</groupId>
    <artifactId>jsoup</artifactId>
    <version>1.13.1</version>
</dependency>

To download the jsoup-1.13.1.jar file you can visit jsoup download page at jsoup.org/download

Using Document.getAllElements() method

Following Java code example using getAllElements() method in jsoup library to find all Elements from a HTML document.

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class GetAllElementsExample1 {
    public static void main(String... args) {
        String htmlContent = "<!DOCTYPE html>" +
                "<html>" +
                "<body>" +
                "<h1>Simple Solution</h1>" +
                "</body>" +
                "</html>";

        Document document = Jsoup.parse(htmlContent);

        Elements elements = document.getAllElements();

        for (Element element : elements) {
            System.out.println(element.tagName());
        }
    }
}
Output:
#root
html
head
body
h1

Using Document.select() method

We also can use select() method with CSS query “*” to find all elements.

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

public class GetAllElementsExample2 {
    public static void main(String... args) {
        String htmlContent = "<!DOCTYPE html>" +
                "<html>" +
                "<body>" +
                "<h1>Simple Solution</h1>" +
                "</body>" +
                "</html>";

        Document document = Jsoup.parse(htmlContent);

        Elements elements = document.select("*");

        for (Element element : elements) {
            System.out.println(element.tagName());
        }
    }
}
Output:
#root
html
head
body
h1

Happy Coding 😊

jsoup Get HTML elements by CSS class name in Java

jsoup Get HTML Element by ID in Java

jsoup Get HTML Elements by Tag Name in Java

jsoup Get HTML Elements by Attribute Name in Java

jsoup Get HTML Elements by Attribute Value in Java

Clean HTML String to get Safe HTML from Untrusted HTML in Java using jsoup