-
Notifications
You must be signed in to change notification settings - Fork 2.3k
Expand file tree
/
Copy pathElement.java
More file actions
2111 lines (1892 loc) · 77.9 KB
/
Element.java
File metadata and controls
2111 lines (1892 loc) · 77.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package org.jsoup.nodes;
import org.jsoup.helper.Validate;
import org.jsoup.internal.Normalizer;
import org.jsoup.internal.QuietAppendable;
import org.jsoup.helper.Regex;
import org.jsoup.internal.StringUtil;
import org.jsoup.parser.ParseSettings;
import org.jsoup.parser.Parser;
import org.jsoup.parser.Tag;
import org.jsoup.parser.TokenQueue;
import org.jsoup.select.Collector;
import org.jsoup.select.Elements;
import org.jsoup.select.Evaluator;
import org.jsoup.select.NodeFilter;
import org.jsoup.select.NodeVisitor;
import org.jsoup.select.Nodes;
import org.jsoup.select.Selector;
import org.jspecify.annotations.Nullable;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
import java.util.regex.Pattern;
import java.util.regex.PatternSyntaxException;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import static org.jsoup.internal.Normalizer.normalize;
import static org.jsoup.nodes.Document.OutputSettings.Syntax.xml;
import static org.jsoup.nodes.TextNode.lastCharIsWhitespace;
import static org.jsoup.parser.Parser.NamespaceHtml;
import static org.jsoup.parser.TokenQueue.escapeCssIdentifier;
import static org.jsoup.select.Selector.evaluatorOf;
/**
An HTML Element consists of a tag name, attributes, and child nodes (including text nodes and other elements).
<p>
From an Element, you can extract data, traverse the node graph, and manipulate the HTML.
*/
public class Element extends Node implements Iterable<Element> {
private static final List<Element> EmptyChildren = Collections.emptyList();
private static final NodeList EmptyNodeList = new NodeList(0);
private static final Pattern ClassSplit = Pattern.compile("\\s+");
static final String BaseUriKey = Attributes.internalKey("baseUri");
Tag tag;
NodeList childNodes;
@Nullable Attributes attributes; // field is nullable but all methods for attributes are non-null
/**
* Create a new, standalone element, in the specified namespace.
* @param tag tag name
* @param namespace namespace for this element
*/
public Element(String tag, String namespace) {
this(Tag.valueOf(tag, namespace, ParseSettings.preserveCase), null);
}
/**
* Create a new, standalone element, in the HTML namespace.
* @param tag tag name
* @see #Element(String tag, String namespace)
*/
public Element(String tag) {
this(tag, Parser.NamespaceHtml);
}
/**
* Create a new, standalone Element. (Standalone in that it has no parent.)
*
* @param tag tag of this element
* @param baseUri the base URI (optional, may be null to inherit from parent, or "" to clear parent's)
* @param attributes initial attributes (optional, may be null)
* @see #appendChild(Node)
* @see #appendElement(String)
*/
public Element(Tag tag, @Nullable String baseUri, @Nullable Attributes attributes) {
Validate.notNull(tag);
childNodes = EmptyNodeList;
this.attributes = attributes;
this.tag = tag;
if (!StringUtil.isBlank(baseUri)) this.setBaseUri(baseUri);
}
/**
* Create a new Element from a Tag and a base URI.
*
* @param tag element tag
* @param baseUri the base URI of this element. Optional, and will inherit from its parent, if any.
* @see Tag#valueOf(String, ParseSettings)
*/
public Element(Tag tag, @Nullable String baseUri) {
this(tag, baseUri, null);
}
/**
Internal test to check if a nodelist object has been created.
*/
protected boolean hasChildNodes() {
return childNodes != EmptyNodeList;
}
@Override protected List<Node> ensureChildNodes() {
if (childNodes == EmptyNodeList) {
childNodes = new NodeList(4);
}
return childNodes;
}
@Override
protected boolean hasAttributes() {
return attributes != null;
}
@Override
public Attributes attributes() {
if (attributes == null) // not using hasAttributes, as doesn't clear warning
attributes = new Attributes();
return attributes;
}
@Override
public String baseUri() {
String baseUri = searchUpForAttribute(this, BaseUriKey);
return baseUri != null ? baseUri : "";
}
@Nullable
static String searchUpForAttribute(final Element start, final String key) {
Element el = start;
while (el != null) {
if (el.attributes != null && el.attributes.hasKey(key))
return el.attributes.get(key);
el = el.parent();
}
return null;
}
@Override
protected void doSetBaseUri(String baseUri) {
attributes().put(BaseUriKey, baseUri);
}
@Override
public int childNodeSize() {
return childNodes.size();
}
@Override
public String nodeName() {
return tag.getName();
}
/**
* Get the name of the tag for this element. E.g. {@code div}. If you are using {@link ParseSettings#preserveCase
* case preserving parsing}, this will return the source's original case.
*
* @return the tag name
*/
public String tagName() {
return tag.getName();
}
/**
* Get the normalized name of this Element's tag. This will always be the lower-cased version of the tag, regardless
* of the tag case preserving setting of the parser. For e.g., {@code <DIV>} and {@code <div>} both have a
* normal name of {@code div}.
* @return normal name
*/
@Override
public String normalName() {
return tag.normalName();
}
/**
Test if this Element has the specified normalized name, and is in the specified namespace.
* @param normalName a normalized element name (e.g. {@code div}).
* @param namespace the namespace
* @return true if the element's normal name matches exactly, and is in the specified namespace
* @since 1.17.2
*/
public boolean elementIs(String normalName, String namespace) {
return tag.normalName().equals(normalName) && tag.namespace().equals(namespace);
}
/**
* Change (rename) the tag of this element. For example, convert a {@code <span>} to a {@code <div>} with
* {@code el.tagName("div");}.
*
* @param tagName new tag name for this element
* @return this element, for chaining
* @see Elements#tagName(String)
*/
public Element tagName(String tagName) {
return tagName(tagName, tag.namespace());
}
/**
* Change (rename) the tag of this element. For example, convert a {@code <span>} to a {@code <div>} with
* {@code el.tagName("div");}.
*
* @param tagName new tag name for this element
* @param namespace the new namespace for this element
* @return this element, for chaining
* @see Elements#tagName(String)
*/
public Element tagName(String tagName, String namespace) {
Validate.notEmptyParam(tagName, "tagName");
Validate.notEmptyParam(namespace, "namespace");
Parser parser = NodeUtils.parser(this);
tag = parser.tagSet().valueOf(tagName, namespace, parser.settings()); // maintains the case option of the original parse
return this;
}
/**
* Get the Tag for this element.
*
* @return the tag object
*/
public Tag tag() {
return tag;
}
/**
Change the Tag of this element.
@param tag the new tag
@return this element, for chaining
@since 1.20.1
*/
public Element tag(Tag tag) {
Validate.notNull(tag);
this.tag = tag;
return this;
}
/**
* Test if this element is a block-level element. (E.g. {@code <div> == true} or an inline element
* {@code <span> == false}).
*
* @return true if block, false if not (and thus inline)
*/
public boolean isBlock() {
return tag.isBlock();
}
/**
* Get the {@code id} attribute of this element.
*
* @return The id attribute, if present, or an empty string if not.
*/
public String id() {
return attributes != null ? attributes.getIgnoreCase("id") :"";
}
/**
Set the {@code id} attribute of this element.
@param id the ID value to use
@return this Element, for chaining
*/
public Element id(String id) {
Validate.notNull(id);
attr("id", id);
return this;
}
/**
* Set an attribute value on this element. If this element already has an attribute with the
* key, its value is updated; otherwise, a new attribute is added.
*
* @return this element
*/
@Override public Element attr(String attributeKey, String attributeValue) {
super.attr(attributeKey, attributeValue);
return this;
}
/**
* Set a boolean attribute value on this element. Setting to <code>true</code> sets the attribute value to "" and
* marks the attribute as boolean so no value is written out. Setting to <code>false</code> removes the attribute
* with the same key if it exists.
*
* @param attributeKey the attribute key
* @param attributeValue the attribute value
*
* @return this element
*/
public Element attr(String attributeKey, boolean attributeValue) {
attributes().put(attributeKey, attributeValue);
return this;
}
/**
Get an Attribute by key. Changes made via {@link Attribute#setKey(String)}, {@link Attribute#setValue(String)} etc
will cascade back to this Element.
@param key the (case-sensitive) attribute key
@return the Attribute for this key, or null if not present.
@since 1.17.2
*/
@Nullable public Attribute attribute(String key) {
return hasAttributes() ? attributes().attribute(key) : null;
}
/**
* Get this element's HTML5 custom data attributes. Each attribute in the element that has a key
* starting with "data-" is included the dataset.
* <p>
* E.g., the element {@code <div data-package="jsoup" data-language="Java" class="group">...} has the dataset
* {@code package=jsoup, language=java}.
* <p>
* This map is a filtered view of the element's attribute map. Changes to one map (add, remove, update) are reflected
* in the other map.
* <p>
* You can find elements that have data attributes using the {@code [^data-]} attribute key prefix selector.
* @return a map of {@code key=value} custom data attributes.
*/
public Map<String, String> dataset() {
return attributes().dataset();
}
@Override @Nullable
public final Element parent() {
return (Element) parentNode;
}
/**
* Get this element's parent and ancestors, up to the document root.
* @return this element's stack of parents, starting with the closest first.
*/
public Elements parents() {
Elements parents = new Elements();
Element parent = this.parent();
while (parent != null && !parent.nameIs("#root")) {
parents.add(parent);
parent = parent.parent();
}
return parents;
}
/**
* Get a child element of this element, by its 0-based index number.
* <p>
* Note that an element can have both mixed Nodes and Elements as children. This method inspects
* a filtered list of children that are elements, and the index is based on that filtered list.
* </p>
*
* @param index the index number of the element to retrieve
* @return the child element, if it exists, otherwise throws an {@code IndexOutOfBoundsException}
* @see #childNode(int)
*/
public Element child(int index) {
Validate.isTrue(index >= 0, "Index must be >= 0");
List<Element> cached = cachedChildren();
if (cached != null) return cached.get(index);
// otherwise, iter on elementChild; saves creating list
int size = childNodes.size();
for (int i = 0, e = 0; i < size; i++) { // direct iter is faster than chasing firstElSib, nextElSibd
Node node = childNodes.get(i);
if (node instanceof Element) {
if (e++ == index) return (Element) node;
}
}
throw new IndexOutOfBoundsException("No child at index: " + index);
}
/**
* Get the number of child nodes of this element that are elements.
* <p>
* This method works on the same filtered list like {@link #child(int)}. Use {@link #childNodes()} and {@link
* #childNodeSize()} to get the unfiltered Nodes (e.g. includes TextNodes etc.)
* </p>
*
* @return the number of child nodes that are elements
* @see #children()
* @see #child(int)
*/
public int childrenSize() {
if (childNodeSize() == 0) return 0;
return childElementsList().size(); // gets children into cache; faster subsequent child(i) if unmodified
}
/**
* Get this element's child elements.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Element nodes.
* </p>
* @return child elements. If this element has no children, returns an empty list.
* @see #childNodes()
*/
public Elements children() {
return new Elements(childElementsList());
}
/**
* Maintains a shadow copy of this element's child elements. If the nodelist is changed, this cache is invalidated.
* @return a list of child elements
*/
List<Element> childElementsList() {
if (childNodeSize() == 0) return EmptyChildren; // short circuit creating empty
// set atomically, so works in multi-thread. Calling methods look like reads, so should be thread-safe
synchronized (childNodes) { // sync vs re-entrant lock, to save another field
List<Element> children = cachedChildren();
if (children == null) {
children = filterNodes(Element.class);
stashChildren(children);
}
return children;
}
}
private static final String childElsKey = "jsoup.childEls";
private static final String childElsMod = "jsoup.childElsMod";
/** returns the cached child els, if they exist, and the modcount of our childnodes matches the stashed modcount */
@Nullable List<Element> cachedChildren() {
if (attributes == null || !attributes.hasUserData()) return null; // don't create empty userdata
Map<String, Object> userData = attributes.userData();
//noinspection unchecked
WeakReference<List<Element>> ref = (WeakReference<List<Element>>) userData.get(childElsKey);
if (ref != null) {
List<Element> els = ref.get();
if (els != null) {
Integer modCount = (Integer) userData.get(childElsMod);
if (modCount != null && modCount == childNodes.modCount())
return els;
}
}
return null;
}
/** caches the child els into the Attribute user data. */
private void stashChildren(List<Element> els) {
Map<String, Object> userData = attributes().userData();
WeakReference<List<Element>> ref = new WeakReference<>(els);
userData.put(childElsKey, ref);
userData.put(childElsMod, childNodes.modCount());
}
/**
Returns a Stream of this Element and all of its descendant Elements. The stream has document order.
@return a stream of this element and its descendants.
@see #nodeStream()
@since 1.17.1
*/
public Stream<Element> stream() {
return NodeUtils.stream(this, Element.class);
}
private <T> List<T> filterNodes(Class<T> clazz) {
return childNodes.stream()
.filter(clazz::isInstance)
.map(clazz::cast)
.collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList));
}
/**
* Get this element's child text nodes. The list is unmodifiable but the text nodes may be manipulated.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Text nodes.
* @return child text nodes. If this element has no text nodes, returns an
* empty list.
* </p>
* For example, with the input HTML: {@code <p>One <span>Two</span> Three <br> Four</p>} with the {@code p} element selected:
* <ul>
* <li>{@code p.text()} = {@code "One Two Three Four"}</li>
* <li>{@code p.ownText()} = {@code "One Three Four"}</li>
* <li>{@code p.children()} = {@code Elements[<span>, <br>]}</li>
* <li>{@code p.childNodes()} = {@code List<Node>["One ", <span>, " Three ", <br>, " Four"]}</li>
* <li>{@code p.textNodes()} = {@code List<TextNode>["One ", " Three ", " Four"]}</li>
* </ul>
*/
public List<TextNode> textNodes() {
return filterNodes(TextNode.class);
}
/**
* Get this element's child data nodes. The list is unmodifiable but the data nodes may be manipulated.
* <p>
* This is effectively a filter on {@link #childNodes()} to get Data nodes.
* </p>
* @return child data nodes. If this element has no data nodes, returns an
* empty list.
* @see #data()
*/
public List<DataNode> dataNodes() {
return filterNodes(DataNode.class);
}
/**
* Find elements that match the {@link Selector} CSS query, with this element as the starting context. Matched elements
* may include this element, or any of its descendents.
* <p>If the query starts with a combinator (e.g. {@code *} or {@code >}), that will combine to this element.</p>
* <p>This method is generally more powerful to use than the DOM-type {@code getElementBy*} methods, because
* multiple filters can be combined, e.g.:</p>
* <ul>
* <li>{@code el.select("a[href]")} - finds links ({@code a} tags with {@code href} attributes)</li>
* <li>{@code el.select("a[href*=example.com]")} - finds links pointing to example.com (loosely)</li>
* <li>{@code el.select("* div")} - finds all divs that descend from this element (and excludes this element)</li>
* <li>{@code el.select("> div")} - finds all divs that are direct children of this element (and excludes this element)</li>
* </ul>
* <p>See the query syntax documentation in {@link org.jsoup.select.Selector}.</p>
* <p>Also known as {@code querySelectorAll()} in the Web DOM.</p>
*
* @param cssQuery a {@link Selector} CSS-like query
* @return an {@link Elements} list containing elements that match the query (empty if none match)
* @see Selector selector query syntax
* @see #select(Evaluator)
* @throws Selector.SelectorParseException (unchecked) on an invalid CSS query.
*/
public Elements select(String cssQuery) {
return Selector.select(cssQuery, this);
}
/**
* Find elements that match the supplied Evaluator. This has the same functionality as {@link #select(String)}, but
* may be useful if you are running the same query many times (on many documents) and want to save the overhead of
* repeatedly parsing the CSS query.
* @param evaluator an element evaluator
* @return an {@link Elements} list containing elements that match the query (empty if none match)
* @see Selector#evaluatorOf(String css)
*/
public Elements select(Evaluator evaluator) {
return Selector.select(evaluator, this);
}
/**
Selects elements from the given root that match the specified {@link Selector} CSS query, with this element as the
starting context, and returns them as a lazy Stream. Matched elements may include this element, or any of its
children.
<p>
Unlike {@link #select(String query)}, which returns a complete list of all matching elements, this method returns a
{@link Stream} that processes elements lazily as they are needed. The stream operates in a "pull" model — elements
are fetched from the root as the stream is traversed. You can use standard {@code Stream} operations such as
{@code filter}, {@code map}, or {@code findFirst} to process elements on demand.
</p>
@param cssQuery a {@link Selector} CSS-like query
@return a {@link Stream} containing elements that match the query (empty if none match)
@throws Selector.SelectorParseException (unchecked) on an invalid CSS query.
@see Selector selector query syntax
@see #selectStream(Evaluator eval)
@since 1.19.1
*/
public Stream<Element> selectStream(String cssQuery) {
return Selector.selectStream(cssQuery, this);
}
/**
Find a Stream of elements that match the supplied Evaluator.
@param evaluator an element Evaluator
@return a {@link Stream} containing elements that match the query (empty if none match)
@see Selector#evaluatorOf(String css)
@since 1.19.1
*/
public Stream<Element> selectStream(Evaluator evaluator) {
return Selector.selectStream(evaluator, this);
}
/**
* Find the first Element that matches the {@link Selector} CSS query, with this element as the starting context.
* <p>This is effectively the same as calling {@code element.select(query).first()}, but is more efficient as query
* execution stops on the first hit.</p>
* <p>Also known as {@code querySelector()} in the Web DOM.</p>
* @param cssQuery cssQuery a {@link Selector} CSS-like query
* @return the first matching element, or <b>{@code null}</b> if there is no match.
* @see #expectFirst(String)
*/
public @Nullable Element selectFirst(String cssQuery) {
return Selector.selectFirst(cssQuery, this);
}
/**
* Finds the first Element that matches the supplied Evaluator, with this element as the starting context, or
* {@code null} if none match.
*
* @param evaluator an element evaluator
* @return the first matching element (walking down the tree, starting from this element), or {@code null} if none
* match.
*/
public @Nullable Element selectFirst(Evaluator evaluator) {
return Collector.findFirst(evaluator, this);
}
/**
Just like {@link #selectFirst(String)}, but if there is no match, throws an {@link IllegalArgumentException}. This
is useful if you want to simply abort processing on a failed match.
@param cssQuery a {@link Selector} CSS-like query
@return the first matching element
@throws IllegalArgumentException if no match is found
@since 1.15.2
*/
public Element expectFirst(String cssQuery) {
return Validate.expectNotNull(
Selector.selectFirst(cssQuery, this),
parent() != null ?
"No elements matched the query '%s' on element '%s'." :
"No elements matched the query '%s' in the document."
, cssQuery, this.tagName()
);
}
/**
Find nodes that match the supplied {@link Evaluator}, with this element as the starting context. Matched
nodes may include this element, or any of its descendents.
@param evaluator an evaluator
@return a list of nodes that match the query (empty if none match)
@since 1.21.1
*/
public Nodes<Node> selectNodes(Evaluator evaluator) {
return selectNodes(evaluator, Node.class);
}
/**
Find nodes that match the supplied {@link Selector} CSS query, with this element as the starting context. Matched
nodes may include this element, or any of its descendents.
<p>To select leaf nodes, the query should specify the node type, e.g. {@code ::text},
{@code ::comment}, {@code ::data}, {@code ::leafnode}.</p>
@param cssQuery a {@link Selector} CSS query
@return a list of nodes that match the query (empty if none match)
@since 1.21.1
*/
public Nodes<Node> selectNodes(String cssQuery) {
return selectNodes(cssQuery, Node.class);
}
/**
Find nodes that match the supplied Evaluator, with this element as the starting context. Matched
nodes may include this element, or any of its descendents.
@param evaluator an evaluator
@param type the type of node to collect (e.g. {@link Element}, {@link LeafNode}, {@link TextNode} etc)
@param <T> the type of node to collect
@return a list of nodes that match the query (empty if none match)
@since 1.21.1
*/
public <T extends Node> Nodes<T> selectNodes(Evaluator evaluator, Class<T> type) {
Validate.notNull(evaluator);
return Collector.collectNodes(evaluator, this, type);
}
/**
Find nodes that match the supplied {@link Selector} CSS query, with this element as the starting context. Matched
nodes may include this element, or any of its descendents.
<p>To select specific node types, use {@code ::text}, {@code ::comment}, {@code ::leafnode}, etc. For example, to
select all text nodes under {@code p} elements: </p>
<pre> Nodes<TextNode> textNodes = doc.selectNodes("p ::text", TextNode.class);</pre>
@param cssQuery a {@link Selector} CSS query
@param type the type of node to collect (e.g. {@link Element}, {@link LeafNode}, {@link TextNode} etc)
@param <T> the type of node to collect
@return a list of nodes that match the query (empty if none match)
@since 1.21.1
*/
public <T extends Node> Nodes<T> selectNodes(String cssQuery, Class<T> type) {
Validate.notEmpty(cssQuery);
return selectNodes(evaluatorOf(cssQuery), type);
}
/**
Find the first Node that matches the {@link Selector} CSS query, with this element as the starting context.
<p>This is effectively the same as calling {@code element.selectNodes(query).first()}, but is more efficient as
query
execution stops on the first hit.</p>
<p>Also known as {@code querySelector()} in the Web DOM.</p>
@param cssQuery cssQuery a {@link Selector} CSS-like query
@return the first matching node, or <b>{@code null}</b> if there is no match.
@since 1.21.1
@see #expectFirst(String)
*/
public @Nullable <T extends Node> T selectFirstNode(String cssQuery, Class<T> type) {
return selectFirstNode(evaluatorOf(cssQuery), type);
}
/**
Finds the first Node that matches the supplied Evaluator, with this element as the starting context, or
{@code null} if none match.
@param evaluator an element evaluator
@return the first matching node (walking down the tree, starting from this element), or {@code null} if none
match.
@since 1.21.1
*/
public @Nullable <T extends Node> T selectFirstNode(Evaluator evaluator, Class<T> type) {
return Collector.findFirstNode(evaluator, this, type);
}
/**
Just like {@link #selectFirstNode(String, Class)}, but if there is no match, throws an
{@link IllegalArgumentException}. This is useful if you want to simply abort processing on a failed match.
@param cssQuery a {@link Selector} CSS-like query
@return the first matching node
@throws IllegalArgumentException if no match is found
@since 1.21.1
*/
public <T extends Node> T expectFirstNode(String cssQuery, Class<T> type) {
return Validate.expectNotNull(
selectFirstNode(cssQuery, type),
parent() != null ?
"No nodes matched the query '%s' on element '%s'.":
"No nodes matched the query '%s' in the document."
, cssQuery, this.tagName()
);
}
/**
* Checks if this element matches the given {@link Selector} CSS query. Also knows as {@code matches()} in the Web
* DOM.
*
* @param cssQuery a {@link Selector} CSS query
* @return if this element matches the query
*/
public boolean is(String cssQuery) {
return is(evaluatorOf(cssQuery));
}
/**
* Check if this element matches the given evaluator.
* @param evaluator an element evaluator
* @return if this element matches
*/
public boolean is(Evaluator evaluator) {
return evaluator.matches(this.root(), this);
}
/**
* Find the closest element up the tree of parents that matches the specified CSS query. Will return itself, an
* ancestor, or {@code null} if there is no such matching element.
* @param cssQuery a {@link Selector} CSS query
* @return the closest ancestor element (possibly itself) that matches the provided evaluator. {@code null} if not
* found.
*/
public @Nullable Element closest(String cssQuery) {
return closest(evaluatorOf(cssQuery));
}
/**
* Find the closest element up the tree of parents that matches the specified evaluator. Will return itself, an
* ancestor, or {@code null} if there is no such matching element.
* @param evaluator a query evaluator
* @return the closest ancestor element (possibly itself) that matches the provided evaluator. {@code null} if not
* found.
*/
public @Nullable Element closest(Evaluator evaluator) {
Validate.notNull(evaluator);
Element el = this;
final Element root = root();
do {
if (evaluator.matches(root, el))
return el;
el = el.parent();
} while (el != null);
return null;
}
/**
Find Elements that match the supplied {@index XPath} expression.
<p>Note that for convenience of writing the Xpath expression, namespaces are disabled, and queries can be
expressed using the element's local name only.</p>
<p>By default, XPath 1.0 expressions are supported. If you would to use XPath 2.0 or higher, you can provide an
alternate XPathFactory implementation:</p>
<ol>
<li>Add the implementation to your classpath. E.g. to use <a href="https://www.saxonica.com/products/products.xml">Saxon-HE</a>, add <a href="https://mvnrepository.com/artifact/net.sf.saxon/Saxon-HE">net.sf.saxon:Saxon-HE</a> to your build.</li>
<li>Set the system property <code>javax.xml.xpath.XPathFactory:jsoup</code> to the implementing classname. E.g.:<br>
<code>System.setProperty(W3CDom.XPathFactoryProperty, "net.sf.saxon.xpath.XPathFactoryImpl");</code>
</li>
</ol>
@param xpath XPath expression
@return matching elements, or an empty list if none match.
@see #selectXpath(String, Class)
@since 1.14.3
*/
public Elements selectXpath(String xpath) {
return new Elements(NodeUtils.selectXpath(xpath, this, Element.class));
}
/**
Find Nodes that match the supplied XPath expression.
<p>For example, to select TextNodes under {@code p} elements: </p>
<pre>List<TextNode> textNodes = doc.selectXpath("//body//p//text()", TextNode.class);</pre>
<p>Note that in the jsoup DOM, Attribute objects are not Nodes. To directly select attribute values, do something
like:</p>
<pre>List<String> hrefs = doc.selectXpath("//a").eachAttr("href");</pre>
@param xpath XPath expression
@param nodeType the jsoup node type to return
@see #selectXpath(String)
@return a list of matching nodes
@since 1.14.3
*/
public <T extends Node> List<T> selectXpath(String xpath, Class<T> nodeType) {
return NodeUtils.selectXpath(xpath, this, nodeType);
}
/**
* Insert a node to the end of this Element's children. The incoming node will be re-parented.
*
* @param child node to add.
* @return this Element, for chaining
* @see #prependChild(Node)
* @see #insertChildren(int, Collection)
*/
public Element appendChild(Node child) {
Validate.notNull(child);
// was - Node#addChildren(child). short-circuits an array create and a loop.
reparentChild(child);
ensureChildNodes();
childNodes.add(child);
child.setSiblingIndex(childNodes.size() - 1);
return this;
}
/**
Insert the given nodes to the end of this Element's children.
@param children nodes to add
@return this Element, for chaining
@see #insertChildren(int, Collection)
*/
public Element appendChildren(Collection<? extends Node> children) {
insertChildren(-1, children);
return this;
}
/**
* Add this element to the supplied parent element, as its next child.
*
* @param parent element to which this element will be appended
* @return this element, so that you can continue modifying the element
*/
public Element appendTo(Element parent) {
Validate.notNull(parent);
parent.appendChild(this);
return this;
}
/**
* Add a node to the start of this element's children.
*
* @param child node to add.
* @return this element, so that you can add more child nodes or elements.
*/
public Element prependChild(Node child) {
Validate.notNull(child);
addChildren(0, child);
return this;
}
/**
Insert the given nodes to the start of this Element's children.
@param children nodes to add
@return this Element, for chaining
@see #insertChildren(int, Collection)
*/
public Element prependChildren(Collection<? extends Node> children) {
insertChildren(0, children);
return this;
}
/**
* Inserts the given child nodes into this element at the specified index. Current nodes will be shifted to the
* right. The inserted nodes will be moved from their current parent. To prevent moving, copy the nodes first.
*
* @param index 0-based index to insert children at. Specify {@code 0} to insert at the start, {@code -1} at the
* end
* @param children child nodes to insert
* @return this element, for chaining.
*/
public Element insertChildren(int index, Collection<? extends Node> children) {
Validate.notNull(children, "Children collection to be inserted must not be null.");
int currentSize = childNodeSize();
if (index < 0) index += currentSize +1; // roll around
Validate.isTrue(index >= 0 && index <= currentSize, "Insert position out of bounds.");
addChildren(index, children.toArray(new Node[0]));
return this;
}
/**
* Inserts the given child nodes into this element at the specified index. Current nodes will be shifted to the
* right. The inserted nodes will be moved from their current parent. To prevent moving, copy the nodes first.
*
* @param index 0-based index to insert children at. Specify {@code 0} to insert at the start, {@code -1} at the
* end
* @param children child nodes to insert
* @return this element, for chaining.
*/
public Element insertChildren(int index, Node... children) {
Validate.notNull(children, "Children collection to be inserted must not be null.");
int currentSize = childNodeSize();
if (index < 0) index += currentSize +1; // roll around
Validate.isTrue(index >= 0 && index <= currentSize, "Insert position out of bounds.");
addChildren(index, children);
return this;
}
/**
* Create a new element by tag name, and add it as this Element's last child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @return the new element, to allow you to add content to it, e.g.:
* {@code parent.appendElement("h1").attr("id", "header").text("Welcome");}
*/
public Element appendElement(String tagName) {
return appendElement(tagName, tag.namespace());
}
/**
* Create a new element by tag name and namespace, add it as this Element's last child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @param namespace the namespace of the tag (e.g. {@link Parser#NamespaceHtml})
* @return the new element, in the specified namespace
*/
public Element appendElement(String tagName, String namespace) {
Parser parser = NodeUtils.parser(this);
Element child = new Element(parser.tagSet().valueOf(tagName, namespace, parser.settings()), baseUri());
appendChild(child);
return child;
}
/**
* Create a new element by tag name, and add it as this Element's first child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @return the new element, to allow you to add content to it, e.g.:
* {@code parent.prependElement("h1").attr("id", "header").text("Welcome");}
*/
public Element prependElement(String tagName) {
return prependElement(tagName, tag.namespace());
}
/**
* Create a new element by tag name and namespace, and add it as this Element's first child.
*
* @param tagName the name of the tag (e.g. {@code div}).
* @param namespace the namespace of the tag (e.g. {@link Parser#NamespaceHtml})
* @return the new element, in the specified namespace
*/
public Element prependElement(String tagName, String namespace) {
Parser parser = NodeUtils.parser(this);
Element child = new Element(parser.tagSet().valueOf(tagName, namespace, parser.settings()), baseUri());
prependChild(child);
return child;
}
/**
* Create and append a new TextNode to this element.
*
* @param text the (un-encoded) text to add
* @return this element
*/
public Element appendText(String text) {
Validate.notNull(text);
TextNode node = new TextNode(text);
appendChild(node);
return this;
}
/**
* Create and prepend a new TextNode to this element.
*
* @param text the decoded text to add
* @return this element
*/
public Element prependText(String text) {
Validate.notNull(text);
TextNode node = new TextNode(text);
prependChild(node);
return this;
}
/**
* Add inner HTML to this element. The supplied HTML will be parsed, and each node appended to the end of the children.
* @param html HTML to add inside this element, after the existing HTML
* @return this element
* @see #html(String)
*/
public Element append(String html) {
Validate.notNull(html);
List<Node> nodes = NodeUtils.parser(this).parseFragmentInput(html, this, baseUri());
addChildren(nodes.toArray(new Node[0]));
return this;
}