user1805792
user1805792

Reputation: 329

How to find a child html element by id with jsoup?

I am parsing the html code of one site with Jsoup. I need to find some html elements that has an specific id but their parent´s tree is complicating me the task. So I would like to know if is it possible to search an specific html element without having to search first all of their parents.

For instance I am doing the next:

Elements el=elements.select(".scroller.context-inplay").select(".zone.grid-1-1").select(".grid-1").select(".module-placeholder");

I would likte to know if there is a simple way to get the same element I get with this code searching by its id

Upvotes: 1

Views: 2035

Answers (1)

luksch
luksch

Reputation: 11712

The id of an html element should be unique within the page. Some html that you find in the wild breaks this requirement unfortunately tough. However, if your html source follows the standard you can simply use the # css operator to select the element in question:

 Element el = doc.select("#someID").first();

Alternatively you can directly use the getElmentById Jsoup method:

Element el = doc.getElmentById("someID");

Also, if you decide to go by class names as you suggest in your question, it is easy to combine all selects into one selector:

Elements els = elements.select(".scroller.context-inplay .zone.grid-1-1 .grid-1 .module-placeholder");

The spaces in the CSS selector mean that any subselector right of the space must be a child of the stuff on the left side.

Upvotes: 1

Related Questions