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 Find the first Element that matches the {@link Selector} CSS query within this element list. 457 <p>This is effectively the same as calling {@code elements.select(query).first()}, but is more efficient as query 458 execution stops on the first hit.</p> 459 460 @param cssQuery a {@link Selector} query 461 @return the first matching element, or <b>{@code null}</b> if there is no match. 462 @see #expectFirst(String) 463 @since 1.19.1 464 */ 465 public @Nullable Element selectFirst(String cssQuery) { 466 return Selector.selectFirst(cssQuery, this); 467 } 468 469 /** 470 Just like {@link #selectFirst(String)}, but if there is no match, throws an {@link IllegalArgumentException}. 471 472 @param cssQuery a {@link Selector} query 473 @return the first matching element 474 @throws IllegalArgumentException if no match is found 475 @since 1.19.1 476 */ 477 public Element expectFirst(String cssQuery) { 478 return (Element) Validate.ensureNotNull( 479 Selector.selectFirst(cssQuery, this), 480 "No elements matched the query '%s' in the elements.", cssQuery 481 ); 482 } 483 484 /** 485 * Remove elements from this list that match the {@link Selector} query. 486 * <p> 487 * E.g. HTML: {@code <div class=logo>One</div> <div>Two</div>}<br> 488 * <code>Elements divs = doc.select("div").not(".logo");</code><br> 489 * Result: {@code divs: [<div>Two</div>]} 490 * <p> 491 * @param query the selector query whose results should be removed from these elements 492 * @return a new elements list that contains only the filtered results 493 */ 494 public Elements not(String query) { 495 Elements out = Selector.select(query, this); 496 return Selector.filterOut(this, out); 497 } 498 499 /** 500 * Get the <i>nth</i> matched element as an Elements object. 501 * <p> 502 * See also {@link #get(int)} to retrieve an Element. 503 * @param index the (zero-based) index of the element in the list to retain 504 * @return Elements containing only the specified element, or, if that element did not exist, an empty list. 505 */ 506 public Elements eq(int index) { 507 return size() > index ? new Elements(get(index)) : new Elements(); 508 } 509 510 /** 511 * Test if any of the matched elements match the supplied query. 512 * @param query A selector 513 * @return true if at least one element in the list matches the query. 514 */ 515 public boolean is(String query) { 516 Evaluator eval = QueryParser.parse(query); 517 for (Element e : this) { 518 if (e.is(eval)) 519 return true; 520 } 521 return false; 522 } 523 524 /** 525 * Get the immediate next element sibling of each element in this list. 526 * @return next element siblings. 527 */ 528 public Elements next() { 529 return siblings(null, true, false); 530 } 531 532 /** 533 * Get the immediate next element sibling of each element in this list, filtered by the query. 534 * @param query CSS query to match siblings against 535 * @return next element siblings. 536 */ 537 public Elements next(String query) { 538 return siblings(query, true, false); 539 } 540 541 /** 542 * Get each of the following element siblings of each element in this list. 543 * @return all following element siblings. 544 */ 545 public Elements nextAll() { 546 return siblings(null, true, true); 547 } 548 549 /** 550 * Get each of the following element siblings of each element in this list, that match the query. 551 * @param query CSS query to match siblings against 552 * @return all following element siblings. 553 */ 554 public Elements nextAll(String query) { 555 return siblings(query, true, true); 556 } 557 558 /** 559 * Get the immediate previous element sibling of each element in this list. 560 * @return previous element siblings. 561 */ 562 public Elements prev() { 563 return siblings(null, false, false); 564 } 565 566 /** 567 * Get the immediate previous element sibling of each element in this list, filtered by the query. 568 * @param query CSS query to match siblings against 569 * @return previous element siblings. 570 */ 571 public Elements prev(String query) { 572 return siblings(query, false, false); 573 } 574 575 /** 576 * Get each of the previous element siblings of each element in this list. 577 * @return all previous element siblings. 578 */ 579 public Elements prevAll() { 580 return siblings(null, false, true); 581 } 582 583 /** 584 * Get each of the previous element siblings of each element in this list, that match the query. 585 * @param query CSS query to match siblings against 586 * @return all previous element siblings. 587 */ 588 public Elements prevAll(String query) { 589 return siblings(query, false, true); 590 } 591 592 private Elements siblings(@Nullable String query, boolean next, boolean all) { 593 Elements els = new Elements(); 594 Evaluator eval = query != null? QueryParser.parse(query) : null; 595 for (Element e : this) { 596 do { 597 Element sib = next ? e.nextElementSibling() : e.previousElementSibling(); 598 if (sib == null) break; 599 if (eval == null || sib.is(eval)) els.add(sib); 600 e = sib; 601 } while (all); 602 } 603 return els; 604 } 605 606 /** 607 * Get all of the parents and ancestor elements of the matched elements. 608 * @return all of the parents and ancestor elements of the matched elements 609 */ 610 public Elements parents() { 611 HashSet<Element> combo = new LinkedHashSet<>(); 612 for (Element e: this) { 613 combo.addAll(e.parents()); 614 } 615 return new Elements(combo); 616 } 617 618 // list-like methods 619 /** 620 Get the first matched element. 621 @return The first matched element, or <code>null</code> if contents is empty. 622 */ 623 public @Nullable Element first() { 624 return isEmpty() ? null : get(0); 625 } 626 627 /** 628 Get the last matched element. 629 @return The last matched element, or <code>null</code> if contents is empty. 630 */ 631 public @Nullable Element last() { 632 return isEmpty() ? null : get(size() - 1); 633 } 634 635 /** 636 * Perform a depth-first traversal on each of the selected elements. 637 * @param nodeVisitor the visitor callbacks to perform on each node 638 * @return this, for chaining 639 */ 640 public Elements traverse(NodeVisitor nodeVisitor) { 641 NodeTraversor.traverse(nodeVisitor, this); 642 return this; 643 } 644 645 /** 646 * Perform a depth-first filtering on each of the selected elements. 647 * @param nodeFilter the filter callbacks to perform on each node 648 * @return this, for chaining 649 */ 650 public Elements filter(NodeFilter nodeFilter) { 651 NodeTraversor.filter(nodeFilter, this); 652 return this; 653 } 654 655 /** 656 * Get the {@link FormElement} forms from the selected elements, if any. 657 * @return a list of {@link FormElement}s pulled from the matched elements. The list will be empty if the elements contain 658 * no forms. 659 */ 660 public List<FormElement> forms() { 661 ArrayList<FormElement> forms = new ArrayList<>(); 662 for (Element el: this) 663 if (el instanceof FormElement) 664 forms.add((FormElement) el); 665 return forms; 666 } 667 668 /** 669 * Get {@link Comment} nodes that are direct child nodes of the selected elements. 670 * @return Comment nodes, or an empty list if none. 671 */ 672 public List<Comment> comments() { 673 return childNodesOfType(Comment.class); 674 } 675 676 /** 677 * Get {@link TextNode} nodes that are direct child nodes of the selected elements. 678 * @return TextNode nodes, or an empty list if none. 679 */ 680 public List<TextNode> textNodes() { 681 return childNodesOfType(TextNode.class); 682 } 683 684 /** 685 * Get {@link DataNode} nodes that are direct child nodes of the selected elements. DataNode nodes contain the 686 * content of tags such as {@code script}, {@code style} etc and are distinct from {@link TextNode}s. 687 * @return Comment nodes, or an empty list if none. 688 */ 689 public List<DataNode> dataNodes() { 690 return childNodesOfType(DataNode.class); 691 } 692 693 private <T extends Node> List<T> childNodesOfType(Class<T> tClass) { 694 ArrayList<T> nodes = new ArrayList<>(); 695 for (Element el: this) { 696 for (int i = 0; i < el.childNodeSize(); i++) { 697 Node node = el.childNode(i); 698 if (tClass.isInstance(node)) 699 nodes.add(tClass.cast(node)); 700 } 701 } 702 return nodes; 703 } 704 705 // list methods that update the DOM: 706 707 /** 708 Replace the Element at the specified index in this list, and in the DOM. 709 * @param index index of the element to replace 710 * @param element element to be stored at the specified position 711 * @return the old Element at this index 712 * @since 1.17.1 713 */ 714 @Override public Element set(int index, Element element) { 715 Validate.notNull(element); 716 Element old = super.set(index, element); 717 old.replaceWith(element); 718 return old; 719 } 720 721 /** 722 Remove the Element at the specified index in this ist, and from the DOM. 723 * @param index the index of the element to be removed 724 * @return the old element at this index 725 * @since 1.17.1 726 */ 727 @Override public Element remove(int index) { 728 Element old = super.remove(index); 729 old.remove(); 730 return old; 731 } 732 733 /** 734 Remove the specified Element from this list, and from th DOM 735 * @param o element to be removed from this list, if present 736 * @return if this list contained the Element 737 * @since 1.17.1 738 */ 739 @Override public boolean remove(Object o) { 740 int index = super.indexOf(o); 741 if (index == -1) { 742 return false; 743 } else { 744 remove(index); 745 return true; 746 } 747 } 748 749 /** 750 Removes all the elements from this list, and each of them from the DOM. 751 * @since 1.17.1 752 * @see #remove() 753 */ 754 @Override public void clear() { 755 remove(); 756 super.clear(); 757 } 758 759 /** 760 Removes from this list, and from the DOM, each of the elements that are contained in the specified collection and 761 are in this list. 762 * @param c collection containing elements to be removed from this list 763 * @return {@code true} if elements were removed from this list 764 * @since 1.17.1 765 */ 766 @Override public boolean removeAll(Collection<?> c) { 767 boolean anyRemoved = false; 768 for (Object o : c) { 769 anyRemoved |= this.remove(o); 770 } 771 return anyRemoved; 772 } 773 774 /** 775 Retain in this list, and in the DOM, only the elements that are in the specified collection and are in this list. 776 In other words, remove elements from this list and the DOM any item that is in this list but not in the specified 777 collection. 778 * @param c collection containing elements to be retained in this list 779 * @return {@code true} if elements were removed from this list 780 * @since 1.17.1 781 */ 782 @Override public boolean retainAll(Collection<?> c) { 783 boolean anyRemoved = false; 784 for (Iterator<Element> it = this.iterator(); it.hasNext(); ) { 785 Element el = it.next(); 786 if (!c.contains(el)) { 787 it.remove(); 788 anyRemoved = true; 789 } 790 } 791 return anyRemoved; 792 } 793 794 /** 795 Remove from the list, and from the DOM, all elements in this list that mach the given filter. 796 * @param filter a predicate which returns {@code true} for elements to be removed 797 * @return {@code true} if elements were removed from this list 798 * @since 1.17.1 799 */ 800 @Override public boolean removeIf(Predicate<? super Element> filter) { 801 boolean anyRemoved = false; 802 for (Iterator<Element> it = this.iterator(); it.hasNext(); ) { 803 Element el = it.next(); 804 if (filter.test(el)) { 805 it.remove(); 806 anyRemoved = true; 807 } 808 } 809 return anyRemoved; 810 } 811 812 /** 813 Replace each element in this list with the result of the operator, and update the DOM. 814 * @param operator the operator to apply to each element 815 * @since 1.17.1 816 */ 817 @Override public void replaceAll(UnaryOperator<Element> operator) { 818 for (int i = 0; i < this.size(); i++) { 819 this.set(i, operator.apply(this.get(i))); 820 } 821 } 822}