Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

Added a forms() convenience method to Elements

This allows one to get at FormElements without casting.
  • Loading branch information...
commit 834d3142304e0927dc659791da6a4521f271d7fd 1 parent 7690381
@jhy authored
View
14 src/main/java/org/jsoup/select/Elements.java
@@ -2,6 +2,7 @@
import org.jsoup.helper.Validate;
import org.jsoup.nodes.Element;
+import org.jsoup.nodes.FormElement;
import org.jsoup.nodes.Node;
import java.util.*;
@@ -487,6 +488,19 @@ public Elements traverse(NodeVisitor nodeVisitor) {
return this;
}
+ /**
+ * Get the {@link FormElement} forms from the selected elements, if any.
+ * @return a list of FormElements pulled from the matched elements. The list will be empty if the elements contain
+ * no forms.
+ */
+ public List<FormElement> forms() {
+ ArrayList<FormElement> forms = new ArrayList<FormElement>();
+ for (Element el: contents)
+ if (el instanceof FormElement)
+ forms.add((FormElement) el);
+ return forms;
+ }
+
// implements List<Element> delegates:
public int size() {return contents.size();}
View
17 src/test/java/org/jsoup/select/ElementsTest.java
@@ -3,8 +3,12 @@
import org.jsoup.Jsoup;
import org.jsoup.TextUtil;
import org.jsoup.nodes.Document;
+import org.jsoup.nodes.FormElement;
import org.jsoup.nodes.Node;
import org.junit.Test;
+
+import java.util.List;
+
import static org.junit.Assert.*;
/**
@@ -252,4 +256,17 @@ public void tail(Node node, int depth) {
});
assertEquals("<div><p><#text></#text></p></div><div><#text></#text></div>", accum.toString());
}
+
+ @Test public void forms() {
+ Document doc = Jsoup.parse("<form id=1><input name=q></form><div /><form id=2><input name=f></form>");
+ Elements els = doc.select("*");
+ assertEquals(9, els.size());
+
+ List<FormElement> forms = els.forms();
+ assertEquals(2, forms.size());
+ assertTrue(forms.get(0) != null);
+ assertTrue(forms.get(1) != null);
+ assertEquals("1", forms.get(0).id());
+ assertEquals("2", forms.get(1).id());
+ }
}

1 comment on commit 834d314

@dma

Hi jhy, does this fix issue #249?

I just sent over a pull request. Thanks for looking at this.

Please sign in to comment.
Something went wrong with that request. Please try again.