Reputation: 59
I have:
Document doc = Jsoup.connect("http://example.com").get();
doc.select(".main li").last().remove();
This is working good if .main li
exists, but if it doesn't exist, then this my application crashes.
How can i check if .main li
exists?
Upvotes: 0
Views: 266
Reputation: 21395
As per JSoup API for Document and Element.html#select(java.lang.String), doc.select(String)
method returns Elements. So you can check for el.size()
to see if it has any elements before deleting the last item.
Elements elements = doc.select(".main li");
if(elements.size() > 0){
elements.last().remove();
}
or you can check if the last
element is not null
before removing it:
Element element = doc.select(".main li").last();
if(element != null){
element.remove();
}
Upvotes: 5