membersound
membersound

Reputation: 86747

How to get a "select" html element by Jsoup?

<section class="my grid">

How can I use Jsoup to optain this element (and all sub elements)? The following does not work (is empty):

Elements ul = doc.getElementsByClass("my grid");

Upvotes: 0

Views: 852

Answers (3)

Syam S
Syam S

Reputation: 8499

This answer is just for your information. This could be done even easier. Just like

Elements ul = doc.select("section.my.grid");

or for iteration as

for(Element section : doc.select("section.my.grid")){
    System.out.println(section.text());
}

Explanation

Esentially you could filter tag based on class by . (DOT) selector. Refer here

For eg - el.class gives all elements with class, e.g. div.masthead selects all div tags with class masthead. So in your case you have two classes "my" and "grid" for section tag. So just filter like

Elements ul = doc.select("section.my");

or

Elements ul = doc.select("section.grid")

This will give you all section tags with a class attribute of my or grid. But in case if you have multiple combination of "my" class and you want just "my" and "grid" together do nesting.

Elements ul = doc.select("section.my.grid");

Upvotes: 1

Benjamin P.
Benjamin P.

Reputation: 453

Classes are separated by a space. In your case you add 2 classes to your section ("my" and "grid").

If you want to have a readable class, use a "-" to separate them.

Upvotes: 0

Hermios
Hermios

Reputation: 634

Elements listGrids=new Elements
for(Element section:doc.getElementsByTag("section"))
{
        if(section.absUrl("Class).equals("my grid")
          listGrids.add(section);
}

I don't know why your current code doesn't work, but it could be because you have a space in your value

Niko

Upvotes: 1

Related Questions