@Test public void testClassNames() { Document doc = Jsoup.parse("<div class=\"c1 c2\">C</div>"); Element div = doc.select("div").get(0); assertEquals("c1 c2", div.className()); final Set<String> set1 = div.classNames(); final Object[] arr1 = set1.toArray(); assertTrue(arr1.length == 2); assertEquals("c1", arr1[0]); assertEquals("c2", arr1[1]); // Changes to the set should not be reflected in the Elements getters set1.add("c3"); assertTrue(2 == div.classNames().size()); assertEquals("c1 c2", div.className()); // Update the class names to a fresh set final Set<String> newSet = new LinkedHashSet<String>(3); newSet.addAll(set1); newSet.add("c3"); div.classNames(newSet); assertEquals("c1 c2 c3", div.className()); final Set<String> set2 = div.classNames(); final Object[] arr2 = set2.toArray(); assertTrue(arr2.length == 3); assertEquals("c1", arr2[0]); assertEquals("c2", arr2[1]); assertEquals("c3", arr2[2]); }
@Test public void testClassUpdates() { Document doc = Jsoup.parse("<div class='mellow yellow'></div>"); Element div = doc.select("div").first(); div.addClass("green"); assertEquals("mellow yellow green", div.className()); div.removeClass("red"); // noop div.removeClass("yellow"); assertEquals("mellow green", div.className()); div.toggleClass("green").toggleClass("red"); assertEquals("mellow red", div.className()); }
@Test public void testClassDomMethods() { Document doc = Jsoup.parse("<div><span class=' mellow yellow '>Hello <b>Yellow</b></span></div>"); List<Element> els = doc.getElementsByAttribute("class"); Element span = els.get(0); assertEquals("mellow yellow", span.className()); assertTrue(span.hasClass("mellow")); assertTrue(span.hasClass("yellow")); Set<String> classes = span.classNames(); assertEquals(2, classes.size()); assertTrue(classes.contains("mellow")); assertTrue(classes.contains("yellow")); assertEquals("", doc.className()); classes = doc.classNames(); assertEquals(0, classes.size()); assertFalse(doc.hasClass("mellow")); }