Skip to content

Commit 834d314

Browse files
committed
Added a forms() convenience method to Elements
This allows one to get at FormElements without casting.
1 parent 7690381 commit 834d314

2 files changed

Lines changed: 31 additions & 0 deletions

File tree

src/main/java/org/jsoup/select/Elements.java

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@
22

33
import org.jsoup.helper.Validate;
44
import org.jsoup.nodes.Element;
5+
import org.jsoup.nodes.FormElement;
56
import org.jsoup.nodes.Node;
67

78
import java.util.*;
@@ -487,6 +488,19 @@ public Elements traverse(NodeVisitor nodeVisitor) {
487488
return this;
488489
}
489490

491+
/**
492+
* Get the {@link FormElement} forms from the selected elements, if any.
493+
* @return a list of FormElements pulled from the matched elements. The list will be empty if the elements contain
494+
* no forms.
495+
*/
496+
public List<FormElement> forms() {
497+
ArrayList<FormElement> forms = new ArrayList<FormElement>();
498+
for (Element el: contents)
499+
if (el instanceof FormElement)
500+
forms.add((FormElement) el);
501+
return forms;
502+
}
503+
490504
// implements List<Element> delegates:
491505
public int size() {return contents.size();}
492506

src/test/java/org/jsoup/select/ElementsTest.java

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,8 +3,12 @@
33
import org.jsoup.Jsoup;
44
import org.jsoup.TextUtil;
55
import org.jsoup.nodes.Document;
6+
import org.jsoup.nodes.FormElement;
67
import org.jsoup.nodes.Node;
78
import org.junit.Test;
9+
10+
import java.util.List;
11+
812
import static org.junit.Assert.*;
913

1014
/**
@@ -252,4 +256,17 @@ public void tail(Node node, int depth) {
252256
});
253257
assertEquals("<div><p><#text></#text></p></div><div><#text></#text></div>", accum.toString());
254258
}
259+
260+
@Test public void forms() {
261+
Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>");
262+
Elements els = doc.select("*");
263+
assertEquals(9, els.size());
264+
265+
List<FormElement> forms = els.forms();
266+
assertEquals(2, forms.size());
267+
assertTrue(forms.get(0) != null);
268+
assertTrue(forms.get(1) != null);
269+
assertEquals("1", forms.get(0).id());
270+
assertEquals("2", forms.get(1).id());
271+
}
255272
}

0 commit comments

Comments
 (0)