Vignesh Prasad
Vignesh Prasad

Reputation: 11

Jsoup select query multiple elements with same class name

This how the DOM looks:

<div class="content-section generic-section">
<div class="content-section generic-section">
<div class="content-section generic-section">

I need to fetch the contents from each div elements. While using select query all three contents are fetched in same variable. how to solve this issue.

Upvotes: 1

Views: 1368

Answers (2)

glytching
glytching

Reputation: 47895

Re this:

While using select query all three contents are fetched in same variable.

All three would be assigned to an instance of Elements which is a type of ArrayList so, in order to interrogate each of these three elements you could

  • Iterate over the ArrayList: for (Element element : elements) { ... }
  • Select entries by position: elements.get(0), elements.get(1) etc
  • Iterate over Elements using prev() and next()
  • Select the first() or last()
  • Use a visitor pattern to traverse() the Elements
  • Get the text of each of the entries: elements.eachText()

Even more options in the Javadocs

Upvotes: 2

fanfanta
fanfanta

Reputation: 181

You can get an Elements object using select method. As @glyching mentioned, you can traverse it. I created test code using forEach like as below.

public void test() {

    Document doc = Jsoup.parse("<html><body><div class=\"content-section generic-section\">contents1</div><div class=\"content-section generic-section\">contents2</div><div class=\"content-section generic-section\">contents3</div></body></html>");
    // get div elements
    Elements elements = doc.select("div.content-section.generic-section");

    // display "contents1" "contents2" "contents3"
    elements.forEach(element -> System.out.println(element.text()));
}

Upvotes: 0

Related Questions