001package org.jsoup.select; 002 003import org.jsoup.helper.Validate; 004import org.jsoup.internal.StringUtil; 005import org.jsoup.nodes.Comment; 006import org.jsoup.nodes.DataNode; 007import org.jsoup.nodes.Element; 008import org.jsoup.nodes.FormElement; 009import org.jsoup.nodes.Node; 010import org.jsoup.nodes.TextNode; 011import org.jspecify.annotations.Nullable; 012 013import java.util.ArrayList; 014import java.util.Arrays; 015import java.util.Collection; 016import java.util.HashSet; 017import java.util.Iterator; 018import java.util.LinkedHashSet; 019import java.util.List; 020import java.util.function.Predicate; 021import java.util.function.UnaryOperator; 022 023/** 024 A list of {@link Element}s, with methods that act on every element in the list. 025 <p>To get an {@code Elements} object, use the {@link Element#select(String)} method.</p> 026 <p>Methods that {@link #set(int, Element) set}, {@link #remove(int) remove}, or {@link #replaceAll(UnaryOperator) 027 replace} Elements in the list will also act on the underlying {@link org.jsoup.nodes.Document DOM}.</p> 028 029 @author Jonathan Hedley, jonathan@hedley.net */ 030public class Elements extends ArrayList<Element> { 031 public Elements() { 032 } 033 034 public Elements(int initialCapacity) { 035 super(initialCapacity); 036 } 037 038 public Elements(Collection<Element> elements) { 039 super(elements); 040 } 041 042 public Elements(List<Element> elements) { 043 super(elements); 044 } 045 046 public Elements(Element... elements) { 047 super(Arrays.asList(elements)); 048 } 049 050 /** 051 * Creates a deep copy of these elements. 052 * @return a deep copy 053 */ 054 @Override 055 public Elements clone() { 056 Elements clone = new Elements(size()); 057 058 for(Element e : this) 059 clone.add(e.clone()); 060 061 return clone; 062 } 063 064 // attribute methods 065 /** 066 Get an attribute value from the first matched element that has the attribute. 067 @param attributeKey The attribute key. 068 @return The attribute value from the first matched element that has the attribute. If no elements were matched (isEmpty() == true), 069 or if the no elements have the attribute, returns empty string. 070 @see #hasAttr(String) 071 */ 072 public String attr(String attributeKey) { 073 for (Element element : this) { 074 if (element.hasAttr(attributeKey)) 075 return element.attr(attributeKey); 076 } 077 return ""; 078 } 079 080 /** 081 Checks if any of the matched elements have this attribute defined. 082 @param attributeKey attribute key 083 @return true if any of the elements have the attribute; false if none do. 084 */ 085 public boolean hasAttr(String attributeKey) { 086 for (Element element : this) { 087 if (element.hasAttr(attributeKey)) 088 return true; 089 } 090 return false; 091 } 092 093 /** 094 * Get the attribute value for each of the matched elements. If an element does not have this attribute, no value is 095 * included in the result set for that element. 096 * @param attributeKey the attribute name to return values for. You can add the {@code abs:} prefix to the key to 097 * get absolute URLs from relative URLs, e.g.: {@code doc.select("a").eachAttr("abs:href")} . 098 * @return a list of each element's attribute value for the attribute 099 */ 100 public List<String> eachAttr(String attributeKey) { 101 List<String> attrs = new ArrayList<>(size()); 102 for (Element element : this) { 103 if (element.hasAttr(attributeKey)) 104 attrs.add(element.attr(attributeKey)); 105 } 106 return attrs; 107 } 108 109 /** 110 * Set an attribute on all matched elements. 111 * @param attributeKey attribute key 112 * @param attributeValue attribute value 113 * @return this 114 */ 115 public Elements attr(String attributeKey, String attributeValue) { 116 for (Element element : this) { 117 element.attr(attributeKey, attributeValue); 118 } 119 return this; 120 } 121 122 /** 123 * Remove an attribute from every matched element. 124 * @param attributeKey The attribute to remove. 125 * @return this (for chaining) 126 */ 127 public Elements removeAttr(String attributeKey) { 128 for (Element element : this) { 129 element.removeAttr(attributeKey); 130 } 131 return this; 132 } 133 134 /** 135 Add the class name to every matched element's {@code class} attribute. 136 @param className class name to add 137 @return this 138 */ 139 public Elements addClass(String className) { 140 for (Element element : this) { 141 element.addClass(className); 142 } 143 return this; 144 } 145 146 /** 147 Remove the class name from every matched element's {@code class} attribute, if present. 148 @param className class name to remove 149 @return this 150 */ 151 public Elements removeClass(String className) { 152 for (Element element : this) { 153 element.removeClass(className); 154 } 155 return this; 156 } 157 158 /** 159 Toggle the class name on every matched element's {@code class} attribute. 160 @param className class name to add if missing, or remove if present, from every element. 161 @return this 162 */ 163 public Elements toggleClass(String className) { 164 for (Element element : this) { 165 element.toggleClass(className); 166 } 167 return this; 168 } 169 170 /** 171 Determine if any of the matched elements have this class name set in their {@code class} attribute. 172 @param className class name to check for 173 @return true if any do, false if none do 174 */ 175 public boolean hasClass(String className) { 176 for (Element element : this) { 177 if (element.hasClass(className)) 178 return true; 179 } 180 return false; 181 } 182 183 /** 184 * Get the form element's value of the first matched element. 185 * @return The form element's value, or empty if not set. 186 * @see Element#val() 187 */ 188 public String val() { 189 if (size() > 0) 190 //noinspection ConstantConditions 191 return first().val(); // first() != null as size() > 0 192 else 193 return ""; 194 } 195 196 /** 197 * Set the form element's value in each of the matched elements. 198 * @param value The value to set into each matched element 199 * @return this (for chaining) 200 */ 201 public Elements val(String value) { 202 for (Element element : this) 203 element.val(value); 204 return this; 205 } 206 207 /** 208 * Get the combined text of all the matched elements. 209 * <p> 210 * Note that it is possible to get repeats if the matched elements contain both parent elements and their own 211 * children, as the Element.text() method returns the combined text of a parent and all its children. 212 * @return string of all text: unescaped and no HTML. 213 * @see Element#text() 214 * @see #eachText() 215 */ 216 public String text() { 217 return stream() 218 .map(Element::text) 219 .collect(StringUtil.joining(" ")); 220 } 221 222 /** 223 Test if any matched Element has any text content, that is not just whitespace. 224 @return true if any element has non-blank text content. 225 @see Element#hasText() 226 */ 227 public boolean hasText() { 228 for (Element element: this) { 229 if (element.hasText()) 230 return true; 231 } 232 return false; 233 } 234 235 /** 236 * Get the text content of each of the matched elements. If an element has no text, then it is not included in the 237 * result. 238 * @return A list of each matched element's text content. 239 * @see Element#text() 240 * @see Element#hasText() 241 * @see #text() 242 */ 243 public List<String> eachText() { 244 ArrayList<String> texts = new ArrayList<>(size()); 245 for (Element el: this) { 246 if (el.hasText()) 247 texts.add(el.text()); 248 } 249 return texts; 250 } 251 252 /** 253 * Get the combined inner HTML of all matched elements. 254 * @return string of all element's inner HTML. 255 * @see #text() 256 * @see #outerHtml() 257 */ 258 public String html() { 259 return stream() 260 .map(Element::html) 261 .collect(StringUtil.joining("\n")); 262 } 263 264 /** 265 * Get the combined outer HTML of all matched elements. 266 * @return string of all element's outer HTML. 267 * @see #text() 268 * @see #html() 269 */ 270 public String outerHtml() { 271 return stream() 272 .map(Element::outerHtml) 273 .collect(StringUtil.joining("\n")); 274 } 275 276 /** 277 * Get the combined outer HTML of all matched elements. Alias of {@link #outerHtml()}. 278 * @return string of all element's outer HTML. 279 * @see #text() 280 * @see #html() 281 */ 282 @Override 283 public String toString() { 284 return outerHtml(); 285 } 286 287 /** 288 * Update (rename) the tag name of each matched element. For example, to change each {@code <i>} to a {@code <em>}, do 289 * {@code doc.select("i").tagName("em");} 290 * 291 * @param tagName the new tag name 292 * @return this, for chaining 293 * @see Element#tagName(String) 294 */ 295 public Elements tagName(String tagName) { 296 for (Element element : this) { 297 element.tagName(tagName); 298 } 299 return this; 300 } 301 302 /** 303 * Set the inner HTML of each matched element. 304 * @param html HTML to parse and set into each matched element. 305 * @return this, for chaining 306 * @see Element#html(String) 307 */ 308 public Elements html(String html) { 309 for (Element element : this) { 310 element.html(html); 311 } 312 return this; 313 } 314 315 /** 316 * Add the supplied HTML to the start of each matched element's inner HTML. 317 * @param html HTML to add inside each element, before the existing HTML 318 * @return this, for chaining 319 * @see Element#prepend(String) 320 */ 321 public Elements prepend(String html) { 322 for (Element element : this) { 323 element.prepend(html); 324 } 325 return this; 326 } 327 328 /** 329 * Add the supplied HTML to the end of each matched element's inner HTML. 330 * @param html HTML to add inside each element, after the existing HTML 331 * @return this, for chaining 332 * @see Element#append(String) 333 */ 334 public Elements append(String html) { 335 for (Element element : this) { 336 element.append(html); 337 } 338 return this; 339 } 340 341 /** 342 * Insert the supplied HTML before each matched element's outer HTML. 343 * @param html HTML to insert before each element 344 * @return this, for chaining 345 * @see Element#before(String) 346 */ 347 public Elements before(String html) { 348 for (Element element : this) { 349 element.before(html); 350 } 351 return this; 352 } 353 354 /** 355 * Insert the supplied HTML after each matched element's outer HTML. 356 * @param html HTML to insert after each element 357 * @return this, for chaining 358 * @see Element#after(String) 359 */ 360 public Elements after(String html) { 361 for (Element element : this) { 362 element.after(html); 363 } 364 return this; 365 } 366 367 /** 368 Wrap the supplied HTML around each matched elements. For example, with HTML 369 {@code <p><b>This</b> is <b>Jsoup</b></p>}, 370 <code>doc.select("b").wrap("<i></i>");</code> 371 becomes {@code <p><i><b>This</b></i> is <i><b>jsoup</b></i></p>} 372 @param html HTML to wrap around each element, e.g. {@code <div class="head"></div>}. Can be arbitrarily deep. 373 @return this (for chaining) 374 @see Element#wrap 375 */ 376 public Elements wrap(String html) { 377 Validate.notEmpty(html); 378 for (Element element : this) { 379 element.wrap(html); 380 } 381 return this; 382 } 383 384 /** 385 * Removes the matched elements from the DOM, and moves their children up into their parents. This has the effect of 386 * dropping the elements but keeping their children. 387 * <p> 388 * This is useful for e.g removing unwanted formatting elements but keeping their contents. 389 * </p> 390 * 391 * E.g. with HTML: <p>{@code <div><font>One</font> <font><a href="/">Two</a></font></div>}</p> 392 * <p>{@code doc.select("font").unwrap();}</p> 393 * <p>HTML = {@code <div>One <a href="/">Two</a></div>}</p> 394 * 395 * @return this (for chaining) 396 * @see Node#unwrap 397 */ 398 public Elements unwrap() { 399 for (Element element : this) { 400 element.unwrap(); 401 } 402 return this; 403 } 404 405 /** 406 * Empty (remove all child nodes from) each matched element. This is similar to setting the inner HTML of each 407 * element to nothing. 408 * <p> 409 * E.g. HTML: {@code <div><p>Hello <b>there</b></p> <p>now</p></div>}<br> 410 * <code>doc.select("p").empty();</code><br> 411 * HTML = {@code <div><p></p> <p></p></div>} 412 * @return this, for chaining 413 * @see Element#empty() 414 * @see #remove() 415 */ 416 public Elements empty() { 417 for (Element element : this) { 418 element.empty(); 419 } 420 return this; 421 } 422 423 /** 424 * Remove each matched element from the DOM. This is similar to setting the outer HTML of each element to nothing. 425 * <p>The elements will still be retained in this list, in case further processing of them is desired.</p> 426 * <p> 427 * E.g. HTML: {@code <div><p>Hello</p> <p>there</p> <img /></div>}<br> 428 * <code>doc.select("p").remove();</code><br> 429 * HTML = {@code <div> <img /></div>} 430 * <p> 431 * Note that this method should not be used to clean user-submitted HTML; rather, use {@link org.jsoup.safety.Cleaner} to clean HTML. 432 * @return this, for chaining 433 * @see Element#empty() 434 * @see #empty() 435 * @see #clear() 436 */ 437 public Elements remove() { 438 for (Element element : this) { 439 element.remove(); 440 } 441 return this; 442 } 443 444 // filters 445 446 /** 447 * Find matching elements within this element list. 448 * @param query A {@link Selector} query 449 * @return the filtered list of elements, or an empty list if none match. 450 */ 451 public Elements select(String query) { 452 return Selector.select(query, this); 453 } 454 455 /** 456 * Remove elements from this list that match the {@link Selector} query. 457 * <p> 458 * E.g. HTML: {@code <div class=logo>One</div> <div>Two</div>}<br> 459 * <code>Elements divs = doc.select("div").not(".logo");</code><br> 460 * Result: {@code divs: [<div>Two</div>]} 461 * <p> 462 * @param query the selector query whose results should be removed from these elements 463 * @return a new elements list that contains only the filtered results 464 */ 465 public Elements not(String query) { 466 Elements out = Selector.select(query, this); 467 return Selector.filterOut(this, out); 468 } 469 470 /** 471 * Get the <i>nth</i> matched element as an Elements object. 472 * <p> 473 * See also {@link #get(int)} to retrieve an Element. 474 * @param index the (zero-based) index of the element in the list to retain 475 * @return Elements containing only the specified element, or, if that element did not exist, an empty list. 476 */ 477 public Elements eq(int index) { 478 return size() > index ? new Elements(get(index)) : new Elements(); 479 } 480 481 /** 482 * Test if any of the matched elements match the supplied query. 483 * @param query A selector 484 * @return true if at least one element in the list matches the query. 485 */ 486 public boolean is(String query) { 487 Evaluator eval = QueryParser.parse(query); 488 for (Element e : this) { 489 if (e.is(eval)) 490 return true; 491 } 492 return false; 493 } 494 495 /** 496 * Get the immediate next element sibling of each element in this list. 497 * @return next element siblings. 498 */ 499 public Elements next() { 500 return siblings(null, true, false); 501 } 502 503 /** 504 * Get the immediate next element sibling of each element in this list, filtered by the query. 505 * @param query CSS query to match siblings against 506 * @return next element siblings. 507 */ 508 public Elements next(String query) { 509 return siblings(query, true, false); 510 } 511 512 /** 513 * Get each of the following element siblings of each element in this list. 514 * @return all following element siblings. 515 */ 516 public Elements nextAll() { 517 return siblings(null, true, true); 518 } 519 520 /** 521 * Get each of the following element siblings of each element in this list, that match the query. 522 * @param query CSS query to match siblings against 523 * @return all following element siblings. 524 */ 525 public Elements nextAll(String query) { 526 return siblings(query, true, true); 527 } 528 529 /** 530 * Get the immediate previous element sibling of each element in this list. 531 * @return previous element siblings. 532 */ 533 public Elements prev() { 534 return siblings(null, false, false); 535 } 536 537 /** 538 * Get the immediate previous element sibling of each element in this list, filtered by the query. 539 * @param query CSS query to match siblings against 540 * @return previous element siblings. 541 */ 542 public Elements prev(String query) { 543 return siblings(query, false, false); 544 } 545 546 /** 547 * Get each of the previous element siblings of each element in this list. 548 * @return all previous element siblings. 549 */ 550 public Elements prevAll() { 551 return siblings(null, false, true); 552 } 553 554 /** 555 * Get each of the previous element siblings of each element in this list, that match the query. 556 * @param query CSS query to match siblings against 557 * @return all previous element siblings. 558 */ 559 public Elements prevAll(String query) { 560 return siblings(query, false, true); 561 } 562 563 private Elements siblings(@Nullable String query, boolean next, boolean all) { 564 Elements els = new Elements(); 565 Evaluator eval = query != null? QueryParser.parse(query) : null; 566 for (Element e : this) { 567 do { 568 Element sib = next ? e.nextElementSibling() : e.previousElementSibling(); 569 if (sib == null) break; 570 if (eval == null) 571 els.add(sib); 572 else if (sib.is(eval)) 573 els.add(sib); 574 e = sib; 575 } while (all); 576 } 577 return els; 578 } 579 580 /** 581 * Get all of the parents and ancestor elements of the matched elements. 582 * @return all of the parents and ancestor elements of the matched elements 583 */ 584 public Elements parents() { 585 HashSet<Element> combo = new LinkedHashSet<>(); 586 for (Element e: this) { 587 combo.addAll(e.parents()); 588 } 589 return new Elements(combo); 590 } 591 592 // list-like methods 593 /** 594 Get the first matched element. 595 @return The first matched element, or <code>null</code> if contents is empty. 596 */ 597 public @Nullable Element first() { 598 return isEmpty() ? null : get(0); 599 } 600 601 /** 602 Get the last matched element. 603 @return The last matched element, or <code>null</code> if contents is empty. 604 */ 605 public @Nullable Element last() { 606 return isEmpty() ? null : get(size() - 1); 607 } 608 609 /** 610 * Perform a depth-first traversal on each of the selected elements. 611 * @param nodeVisitor the visitor callbacks to perform on each node 612 * @return this, for chaining 613 */ 614 public Elements traverse(NodeVisitor nodeVisitor) { 615 NodeTraversor.traverse(nodeVisitor, this); 616 return this; 617 } 618 619 /** 620 * Perform a depth-first filtering on each of the selected elements. 621 * @param nodeFilter the filter callbacks to perform on each node 622 * @return this, for chaining 623 */ 624 public Elements filter(NodeFilter nodeFilter) { 625 NodeTraversor.filter(nodeFilter, this); 626 return this; 627 } 628 629 /** 630 * Get the {@link FormElement} forms from the selected elements, if any. 631 * @return a list of {@link FormElement}s pulled from the matched elements. The list will be empty if the elements contain 632 * no forms. 633 */ 634 public List<FormElement> forms() { 635 ArrayList<FormElement> forms = new ArrayList<>(); 636 for (Element el: this) 637 if (el instanceof FormElement) 638 forms.add((FormElement) el); 639 return forms; 640 } 641 642 /** 643 * Get {@link Comment} nodes that are direct child nodes of the selected elements. 644 * @return Comment nodes, or an empty list if none. 645 */ 646 public List<Comment> comments() { 647 return childNodesOfType(Comment.class); 648 } 649 650 /** 651 * Get {@link TextNode} nodes that are direct child nodes of the selected elements. 652 * @return TextNode nodes, or an empty list if none. 653 */ 654 public List<TextNode> textNodes() { 655 return childNodesOfType(TextNode.class); 656 } 657 658 /** 659 * Get {@link DataNode} nodes that are direct child nodes of the selected elements. DataNode nodes contain the 660 * content of tags such as {@code script}, {@code style} etc and are distinct from {@link TextNode}s. 661 * @return Comment nodes, or an empty list if none. 662 */ 663 public List<DataNode> dataNodes() { 664 return childNodesOfType(DataNode.class); 665 } 666 667 private <T extends Node> List<T> childNodesOfType(Class<T> tClass) { 668 ArrayList<T> nodes = new ArrayList<>(); 669 for (Element el: this) { 670 for (int i = 0; i < el.childNodeSize(); i++) { 671 Node node = el.childNode(i); 672 if (tClass.isInstance(node)) 673 nodes.add(tClass.cast(node)); 674 } 675 } 676 return nodes; 677 } 678 679 // list methods that update the DOM: 680 681 /** 682 Replace the Element at the specified index in this list, and in the DOM. 683 * @param index index of the element to replace 684 * @param element element to be stored at the specified position 685 * @return the old Element at this index 686 * @since 1.17.1 687 */ 688 @Override public Element set(int index, Element element) { 689 Validate.notNull(element); 690 Element old = super.set(index, element); 691 old.replaceWith(element); 692 return old; 693 } 694 695 /** 696 Remove the Element at the specified index in this ist, and from the DOM. 697 * @param index the index of the element to be removed 698 * @return the old element at this index 699 * @since 1.17.1 700 */ 701 @Override public Element remove(int index) { 702 Element old = super.remove(index); 703 old.remove(); 704 return old; 705 } 706 707 /** 708 Remove the specified Element from this list, and from th DOM 709 * @param o element to be removed from this list, if present 710 * @return if this list contained the Element 711 * @since 1.17.1 712 */ 713 @Override public boolean remove(Object o) { 714 int index = super.indexOf(o); 715 if (index == -1) { 716 return false; 717 } else { 718 remove(index); 719 return true; 720 } 721 } 722 723 /** 724 Removes all the elements from this list, and each of them from the DOM. 725 * @since 1.17.1 726 * @see #remove() 727 */ 728 @Override public void clear() { 729 remove(); 730 super.clear(); 731 } 732 733 /** 734 Removes from this list, and from the DOM, each of the elements that are contained in the specified collection and 735 are in this list. 736 * @param c collection containing elements to be removed from this list 737 * @return {@code true} if elements were removed from this list 738 * @since 1.17.1 739 */ 740 @Override public boolean removeAll(Collection<?> c) { 741 boolean anyRemoved = false; 742 for (Object o : c) { 743 anyRemoved |= this.remove(o); 744 } 745 return anyRemoved; 746 } 747 748 /** 749 Retain in this list, and in the DOM, only the elements that are in the specified collection and are in this list. 750 In other words, remove elements from this list and the DOM any item that is in this list but not in the specified 751 collection. 752 * @param c collection containing elements to be retained in this list 753 * @return {@code true} if elements were removed from this list 754 * @since 1.17.1 755 */ 756 @Override public boolean retainAll(Collection<?> c) { 757 boolean anyRemoved = false; 758 for (Iterator<Element> it = this.iterator(); it.hasNext(); ) { 759 Element el = it.next(); 760 if (!c.contains(el)) { 761 it.remove(); 762 anyRemoved = true; 763 } 764 } 765 return anyRemoved; 766 } 767 768 /** 769 Remove from the list, and from the DOM, all elements in this list that mach the given filter. 770 * @param filter a predicate which returns {@code true} for elements to be removed 771 * @return {@code true} if elements were removed from this list 772 * @since 1.17.1 773 */ 774 @Override public boolean removeIf(Predicate<? super Element> filter) { 775 boolean anyRemoved = false; 776 for (Iterator<Element> it = this.iterator(); it.hasNext(); ) { 777 Element el = it.next(); 778 if (filter.test(el)) { 779 it.remove(); 780 anyRemoved = true; 781 } 782 } 783 return anyRemoved; 784 } 785 786 /** 787 Replace each element in this list with the result of the operator, and update the DOM. 788 * @param operator the operator to apply to each element 789 * @since 1.17.1 790 */ 791 @Override public void replaceAll(UnaryOperator<Element> operator) { 792 for (int i = 0; i < this.size(); i++) { 793 this.set(i, operator.apply(this.get(i))); 794 } 795 } 796}