Skip to content
This repository
Browse code

Added a forms() convenience method to Elements

This allows one to get at FormElements without casting.
  • Loading branch information...
commit 834d3142304e0927dc659791da6a4521f271d7fd 1 parent 7690381
Jonathan Hedley authored February 16, 2013
14  src/main/java/org/jsoup/select/Elements.java
@@ -2,6 +2,7 @@
2 2
 
3 3
 import org.jsoup.helper.Validate;
4 4
 import org.jsoup.nodes.Element;
  5
+import org.jsoup.nodes.FormElement;
5 6
 import org.jsoup.nodes.Node;
6 7
 
7 8
 import java.util.*;
@@ -487,6 +488,19 @@ public Elements traverse(NodeVisitor nodeVisitor) {
487 488
         return this;
488 489
     }
489 490
 
  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
+
490 504
     // implements List<Element> delegates:
491 505
     public int size() {return contents.size();}
492 506
 
17  src/test/java/org/jsoup/select/ElementsTest.java
@@ -3,8 +3,12 @@
3 3
 import org.jsoup.Jsoup;
4 4
 import org.jsoup.TextUtil;
5 5
 import org.jsoup.nodes.Document;
  6
+import org.jsoup.nodes.FormElement;
6 7
 import org.jsoup.nodes.Node;
7 8
 import org.junit.Test;
  9
+
  10
+import java.util.List;
  11
+
8 12
 import static org.junit.Assert.*;
9 13
 
10 14
 /**
@@ -252,4 +256,17 @@ public void tail(Node node, int depth) {
252 256
         });
253 257
         assertEquals("<div><p><#text></#text></p></div><div><#text></#text></div>", accum.toString());
254 258
     }
  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
+    }
255 272
 }

1 note on commit 834d314

David

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.