View Javadoc
1   /*
2    * Copyright (c) 2002-2026 Gargoyle Software Inc.
3    *
4    * Licensed under the Apache License, Version 2.0 (the "License");
5    * you may not use this file except in compliance with the License.
6    * You may obtain a copy of the License at
7    * https://www.apache.org/licenses/LICENSE-2.0
8    *
9    * Unless required by applicable law or agreed to in writing, software
10   * distributed under the License is distributed on an "AS IS" BASIS,
11   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12   * See the License for the specific language governing permissions and
13   * limitations under the License.
14   */
15  package org.htmlunit.html;
16  
17  import java.io.IOException;
18  import java.io.PrintWriter;
19  import java.io.Serializable;
20  import java.io.StringWriter;
21  import java.nio.charset.Charset;
22  import java.util.ArrayList;
23  import java.util.HashMap;
24  import java.util.Iterator;
25  import java.util.List;
26  import java.util.Map;
27  import java.util.NoSuchElementException;
28  import java.util.concurrent.CopyOnWriteArrayList;
29  
30  import org.htmlunit.BrowserVersionFeatures;
31  import org.htmlunit.IncorrectnessListener;
32  import org.htmlunit.Page;
33  import org.htmlunit.SgmlPage;
34  import org.htmlunit.WebAssert;
35  import org.htmlunit.WebClient;
36  import org.htmlunit.WebClient.PooledCSS3Parser;
37  import org.htmlunit.WebWindow;
38  import org.htmlunit.css.ComputedCssStyleDeclaration;
39  import org.htmlunit.css.CssStyleSheet;
40  import org.htmlunit.css.StyleAttributes;
41  import org.htmlunit.cssparser.parser.CSSErrorHandler;
42  import org.htmlunit.cssparser.parser.CSSException;
43  import org.htmlunit.cssparser.parser.CSSOMParser;
44  import org.htmlunit.cssparser.parser.CSSParseException;
45  import org.htmlunit.cssparser.parser.selector.Selector;
46  import org.htmlunit.cssparser.parser.selector.SelectorList;
47  import org.htmlunit.html.HtmlElement.DisplayStyle;
48  import org.htmlunit.html.serializer.HtmlSerializerNormalizedText;
49  import org.htmlunit.html.serializer.HtmlSerializerVisibleText;
50  import org.htmlunit.html.xpath.XPathHelper;
51  import org.htmlunit.javascript.HtmlUnitScriptable;
52  import org.htmlunit.javascript.host.event.Event;
53  import org.htmlunit.xpath.xml.utils.PrefixResolver;
54  import org.w3c.dom.DOMException;
55  import org.w3c.dom.Document;
56  import org.w3c.dom.NamedNodeMap;
57  import org.w3c.dom.Node;
58  import org.w3c.dom.UserDataHandler;
59  import org.xml.sax.SAXException;
60  
61  /**
62   * Base class for nodes in the HTML DOM tree. This class is modeled after the
63   * W3C DOM specification, but does not implement it.
64   *
65   * @author Mike Bowler
66   * @author Mike J. Bresnahan
67   * @author David K. Taylor
68   * @author Christian Sell
69   * @author Chris Erskine
70   * @author Mike Williams
71   * @author Marc Guillemot
72   * @author Denis N. Antonioli
73   * @author Daniel Gredler
74   * @author Ahmed Ashour
75   * @author Rodney Gitzel
76   * @author Sudhan Moghe
77   * @author Tom Anderson
78   * @author Ronald Brill
79   * @author Chuck Dumont
80   * @author Frank Danek
81   * @author Lai Quang Duong
82   */
83  public abstract class DomNode implements Cloneable, Serializable, Node {
84  
85      /** A ready state constant (state 1). */
86      public static final String READY_STATE_UNINITIALIZED = "uninitialized";
87  
88      /** A ready state constant (state 2). */
89      public static final String READY_STATE_LOADING = "loading";
90  
91      /** A ready state constant (state 3). */
92      public static final String READY_STATE_LOADED = "loaded";
93  
94      /** A ready state constant (state 4). */
95      public static final String READY_STATE_INTERACTIVE = "interactive";
96  
97      /** A ready state constant (state 5). */
98      public static final String READY_STATE_COMPLETE = "complete";
99  
100     /** The name of the "element" property. Used when watching property change events. */
101     public static final String PROPERTY_ELEMENT = "element";
102 
103     private static final NamedNodeMap EMPTY_NAMED_NODE_MAP = new ReadOnlyEmptyNamedNodeMapImpl();
104 
105     /** The owning page of this node. */
106     private SgmlPage page_;
107 
108     /** The parent node. */
109     private DomNode parent_;
110 
111     /**
112      * The previous sibling. The first child's <code>previousSibling</code> points
113      * to the end of the list
114      */
115     private DomNode previousSibling_;
116 
117     /**
118      * The next sibling. The last child's <code>nextSibling</code> is {@code null}
119      */
120     private DomNode nextSibling_;
121 
122     /** Start of the child list. */
123     private DomNode firstChild_;
124 
125     /**
126      * This is the JavaScript object corresponding to this DOM node. It may
127      * be null if there isn't a corresponding JavaScript object.
128      */
129     private HtmlUnitScriptable scriptObject_;
130 
131     /** The ready state is a value that is available to a large number of elements. */
132     private String readyState_;
133 
134     /**
135      * The line number in the source page where the DOM node starts.
136      */
137     private int startLineNumber_ = -1;
138 
139     /**
140      * The column number in the source page where the DOM node starts.
141      */
142     private int startColumnNumber_ = -1;
143 
144     /**
145      * The line number in the source page where the DOM node ends.
146      */
147     private int endLineNumber_ = -1;
148 
149     /**
150      * The column number in the source page where the DOM node ends.
151      */
152     private int endColumnNumber_ = -1;
153 
154     private boolean attachedToPage_;
155 
156     // The listener lists are created lazily (inside a synchronized block). Listeners are added/removed rarely
157     // but the lists are read for every change of the dom tree; CopyOnWriteArrayList allows to iterate
158     // without a lock and without a copy.
159     /** The listeners which are to be notified of characterData change. */
160     private volatile List<CharacterDataChangeListener> characterDataListeners_;
161     /** The listeners which are to be notified of dom changes. */
162     private volatile List<DomChangeListener> domListeners_;
163 
164     private Map<String, Object> userData_;
165 
166     /**
167      * Creates a new instance.
168      * @param page the page which contains this node
169      */
170     protected DomNode(final SgmlPage page) {
171         readyState_ = READY_STATE_LOADING;
172         page_ = page;
173     }
174 
175     /**
176      * Sets the line and column numbers in the source page where the DOM node starts.
177      *
178      * @param startLineNumber the line number where the DOM node starts
179      * @param startColumnNumber the column number where the DOM node starts
180      */
181     public void setStartLocation(final int startLineNumber, final int startColumnNumber) {
182         startLineNumber_ = startLineNumber;
183         startColumnNumber_ = startColumnNumber;
184     }
185 
186     /**
187      * Sets the line and column numbers in the source page where the DOM node ends.
188      *
189      * @param endLineNumber the line number where the DOM node ends
190      * @param endColumnNumber the column number where the DOM node ends
191      */
192     public void setEndLocation(final int endLineNumber, final int endColumnNumber) {
193         endLineNumber_ = endLineNumber;
194         endColumnNumber_ = endColumnNumber;
195     }
196 
197     /**
198      * Returns the line number in the source page where the DOM node starts.
199      * @return the line number in the source page where the DOM node starts
200      */
201     public int getStartLineNumber() {
202         return startLineNumber_;
203     }
204 
205     /**
206      * Returns the column number in the source page where the DOM node starts.
207      * @return the column number in the source page where the DOM node starts
208      */
209     public int getStartColumnNumber() {
210         return startColumnNumber_;
211     }
212 
213     /**
214      * Returns the line number in the source page where the DOM node ends.
215      * @return 0 if no information on the line number is available (for instance for nodes dynamically added),
216      *         -1 if the end tag has not yet been parsed (during page loading)
217      */
218     public int getEndLineNumber() {
219         return endLineNumber_;
220     }
221 
222     /**
223      * Returns the column number in the source page where the DOM node ends.
224      * @return 0 if no information on the line number is available (for instance for nodes dynamically added),
225      *         -1 if the end tag has not yet been parsed (during page loading)
226      */
227     public int getEndColumnNumber() {
228         return endColumnNumber_;
229     }
230 
231     /**
232      * Returns the page that contains this node.
233      * @return the page that contains this node
234      */
235     public SgmlPage getPage() {
236         return page_;
237     }
238 
239     /**
240      * Returns the page that contains this node.
241      * @return the page that contains this node
242      */
243     public HtmlPage getHtmlPageOrNull() {
244         if (page_ == null || !page_.isHtmlPage()) {
245             return null;
246         }
247         return (HtmlPage) page_;
248     }
249 
250     /**
251      * {@inheritDoc}
252      */
253     @Override
254     public Document getOwnerDocument() {
255         return getPage();
256     }
257 
258     /**
259      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
260      *
261      * Sets the JavaScript object that corresponds to this node. This is not guaranteed to be set even if
262      * there is a JavaScript object for this DOM node.
263      *
264      * @param scriptObject the JavaScript object
265      */
266     public void setScriptableObject(final HtmlUnitScriptable scriptObject) {
267         scriptObject_ = scriptObject;
268     }
269 
270     /**
271      * {@inheritDoc}
272      */
273     @Override
274     public DomNode getLastChild() {
275         if (firstChild_ != null) {
276             // last child is stored as the previous sibling of first child
277             return firstChild_.previousSibling_;
278         }
279         return null;
280     }
281 
282     /**
283      * {@inheritDoc}
284      */
285     @Override
286     public DomNode getParentNode() {
287         return parent_;
288     }
289 
290     /**
291      * Sets the parent node.
292      * @param parent the parent node
293      */
294     protected void setParentNode(final DomNode parent) {
295         parent_ = parent;
296     }
297 
298     /**
299      * Returns this node's index within its parent's child nodes (zero-based).
300      * @return this node's index within its parent's child nodes (zero-based)
301      */
302     public int getIndex() {
303         int index = 0;
304         for (DomNode n = previousSibling_; n != null && n.nextSibling_ != null; n = n.previousSibling_) {
305             index++;
306         }
307         return index;
308     }
309 
310     /**
311      * {@inheritDoc}
312      */
313     @Override
314     public DomNode getPreviousSibling() {
315         if (parent_ == null || this == parent_.firstChild_) {
316             // previous sibling of first child points to last child
317             return null;
318         }
319         return previousSibling_;
320     }
321 
322     /**
323      * {@inheritDoc}
324      */
325     @Override
326     public DomNode getNextSibling() {
327         return nextSibling_;
328     }
329 
330     /**
331      * {@inheritDoc}
332      */
333     @Override
334     public DomNode getFirstChild() {
335         return firstChild_;
336     }
337 
338     /**
339      * Returns {@code true} if this node is an ancestor of the specified node.
340      *
341      * @param node the node to check
342      * @return {@code true} if this node is an ancestor of the specified node
343      */
344     public boolean isAncestorOf(final DomNode node) {
345         DomNode parent = node;
346         while (parent != null) {
347             if (parent == this) {
348                 return true;
349             }
350             parent = parent.getParentNode();
351         }
352         return false;
353     }
354 
355     /**
356      * Returns {@code true} if this node is an ancestor of the specified nodes.
357      *
358      * @param nodes the nodes to check
359      * @return {@code true} if this node is an ancestor of the specified nodes
360      */
361     public boolean isAncestorOfAny(final DomNode... nodes) {
362         for (final DomNode node : nodes) {
363             if (isAncestorOf(node)) {
364                 return true;
365             }
366         }
367         return false;
368     }
369 
370     /**
371      * {@inheritDoc}
372      */
373     @Override
374     public String getNamespaceURI() {
375         return null;
376     }
377 
378     /**
379      * {@inheritDoc}
380      */
381     @Override
382     public String getLocalName() {
383         return null;
384     }
385 
386     /**
387      * {@inheritDoc}
388      */
389     @Override
390     public String getPrefix() {
391         return null;
392     }
393 
394     /**
395      * {@inheritDoc}
396      */
397     @Override
398     public boolean hasChildNodes() {
399         return firstChild_ != null;
400     }
401 
402     /**
403      * {@inheritDoc}
404      */
405     @Override
406     public DomNodeList<DomNode> getChildNodes() {
407         return new SiblingDomNodeList(this);
408     }
409 
410     /**
411      * {@inheritDoc}
412      * Not yet implemented.
413      */
414     @Override
415     public boolean isSupported(final String namespace, final String featureName) {
416         throw new UnsupportedOperationException("DomNode.isSupported is not yet implemented.");
417     }
418 
419     /**
420      * {@inheritDoc}
421      */
422     @Override
423     public void normalize() {
424         for (DomNode child = getFirstChild(); child != null; child = child.getNextSibling()) {
425             if (child instanceof DomText) {
426                 final StringBuilder dataBuilder = new StringBuilder();
427                 DomNode toRemove = child;
428                 DomText firstText = null;
429                 while (toRemove instanceof DomText && !(toRemove instanceof DomCDataSection)) {
430                     final DomNode nextChild = toRemove.getNextSibling();
431                     dataBuilder.append(toRemove.getTextContent());
432                     if (firstText != null) {
433                         toRemove.remove();
434                     }
435                     if (firstText == null) {
436                         firstText = (DomText) toRemove;
437                     }
438                     toRemove = nextChild;
439                 }
440                 if (firstText != null) {
441                     firstText.setData(dataBuilder.toString());
442                 }
443             }
444             else {
445                 // recurse so text runs nested inside child elements get merged too
446                 child.normalize();
447             }
448         }
449     }
450 
451     /**
452      * {@inheritDoc}
453      */
454     @Override
455     public String getBaseURI() {
456         return getPage().getUrl().toExternalForm();
457     }
458 
459     /**
460      * {@inheritDoc}
461      */
462     @Override
463     public short compareDocumentPosition(final Node other) {
464         if (other == this) {
465             return 0; // strange, no constant available?
466         }
467 
468         // get ancestors of both
469         final List<Node> myAncestors = getAncestors();
470         final List<Node> otherAncestors = ((DomNode) other).getAncestors();
471 
472         if (!myAncestors.get(0).equals(otherAncestors.get(0))) {
473             // spec likes to have a consistent order
474             //
475             // If ... node1’s root is not node2’s root, then return the result of adding
476             // DOCUMENT_POSITION_DISCONNECTED, DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC,
477             // and either DOCUMENT_POSITION_PRECEDING or DOCUMENT_POSITION_FOLLOWING,
478             // with the constraint that this is to be consistent...
479             if (this.hashCode() < other.hashCode()) {
480                 return DOCUMENT_POSITION_DISCONNECTED
481                         | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
482                         | DOCUMENT_POSITION_PRECEDING;
483             }
484 
485             return DOCUMENT_POSITION_DISCONNECTED
486                     | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
487                     | DOCUMENT_POSITION_FOLLOWING;
488         }
489 
490         final int max = Math.min(myAncestors.size(), otherAncestors.size());
491 
492         int i = 1;
493         while (i < max && myAncestors.get(i) == otherAncestors.get(i)) {
494             i++;
495         }
496 
497         if (i != 1 && i == max) {
498             if (myAncestors.size() == max) {
499                 return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
500             }
501             return DOCUMENT_POSITION_CONTAINS | DOCUMENT_POSITION_PRECEDING;
502         }
503 
504         if (max == 1) {
505             if (myAncestors.contains(other)) {
506                 return DOCUMENT_POSITION_CONTAINS;
507             }
508             if (otherAncestors.contains(this)) {
509                 return DOCUMENT_POSITION_CONTAINED_BY | DOCUMENT_POSITION_FOLLOWING;
510             }
511             return DOCUMENT_POSITION_DISCONNECTED | DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
512         }
513 
514         // neither contains nor contained by
515         final Node myAncestor = myAncestors.get(i);
516         final Node otherAncestor = otherAncestors.get(i);
517         Node node = myAncestor;
518         while (node != otherAncestor && node != null) {
519             node = node.getPreviousSibling();
520         }
521         if (node == null) {
522             return DOCUMENT_POSITION_FOLLOWING;
523         }
524         return DOCUMENT_POSITION_PRECEDING;
525     }
526 
527     /**
528      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
529      *
530      * Gets the ancestors of the node.
531      * @return a list of the ancestors with the root at the first position
532      */
533     public List<Node> getAncestors() {
534         final List<Node> list = new ArrayList<>();
535         list.add(this);
536 
537         Node node = getParentNode();
538         while (node != null) {
539             list.add(0, node);
540             node = node.getParentNode();
541         }
542         return list;
543     }
544 
545     /**
546      * {@inheritDoc}
547      */
548     @Override
549     public String getTextContent() {
550         switch (getNodeType()) {
551             case ELEMENT_NODE:
552             case ATTRIBUTE_NODE:
553             case ENTITY_NODE:
554             case ENTITY_REFERENCE_NODE:
555             case DOCUMENT_FRAGMENT_NODE:
556                 final StringBuilder builder = new StringBuilder();
557                 for (final DomNode child : getChildren()) {
558                     final short childType = child.getNodeType();
559                     if (childType != COMMENT_NODE && childType != PROCESSING_INSTRUCTION_NODE) {
560                         builder.append(child.getTextContent());
561                     }
562                 }
563                 return builder.toString();
564 
565             case TEXT_NODE:
566             case CDATA_SECTION_NODE:
567             case COMMENT_NODE:
568             case PROCESSING_INSTRUCTION_NODE:
569                 return getNodeValue();
570 
571             default:
572                 return null;
573         }
574     }
575 
576     /**
577      * {@inheritDoc}
578      */
579     @Override
580     public void setTextContent(final String textContent) {
581         removeAllChildren();
582         if (textContent != null && !textContent.isEmpty()) {
583             appendChild(new DomText(getPage(), textContent));
584         }
585     }
586 
587     /**
588      * {@inheritDoc}
589      */
590     @Override
591     public boolean isSameNode(final Node other) {
592         return other == this;
593     }
594 
595     /**
596      * {@inheritDoc}
597      * Not yet implemented.
598      */
599     @Override
600     public String lookupPrefix(final String namespaceURI) {
601         throw new UnsupportedOperationException("DomNode.lookupPrefix is not yet implemented.");
602     }
603 
604     /**
605      * {@inheritDoc}
606      * Not yet implemented.
607      */
608     @Override
609     public boolean isDefaultNamespace(final String namespaceURI) {
610         throw new UnsupportedOperationException("DomNode.isDefaultNamespace is not yet implemented.");
611     }
612 
613     /**
614      * {@inheritDoc}
615      * Not yet implemented.
616      */
617     @Override
618     public String lookupNamespaceURI(final String prefix) {
619         throw new UnsupportedOperationException("DomNode.lookupNamespaceURI is not yet implemented.");
620     }
621 
622     /**
623      * {@inheritDoc}
624      * Not yet implemented.
625      */
626     @Override
627     public boolean isEqualNode(final Node arg) {
628         throw new UnsupportedOperationException("DomNode.isEqualNode is not yet implemented.");
629     }
630 
631     /**
632      * {@inheritDoc}
633      * Not yet implemented.
634      */
635     @Override
636     public Object getFeature(final String feature, final String version) {
637         throw new UnsupportedOperationException("DomNode.getFeature is not yet implemented.");
638     }
639 
640     /**
641      * {@inheritDoc}
642      */
643     @Override
644     public Object getUserData(final String key) {
645         Object value = null;
646         if (userData_ != null) {
647             value = userData_.get(key);
648         }
649         return value;
650     }
651 
652     /**
653      * {@inheritDoc}
654      */
655     @Override
656     public Object setUserData(final String key, final Object data, final UserDataHandler handler) {
657         if (userData_ == null) {
658             userData_ = new HashMap<>();
659         }
660         return userData_.put(key, data);
661     }
662 
663     /**
664      * {@inheritDoc}
665      */
666     @Override
667     public boolean hasAttributes() {
668         return false;
669     }
670 
671     /**
672      * {@inheritDoc}
673      */
674     @Override
675     public NamedNodeMap getAttributes() {
676         return EMPTY_NAMED_NODE_MAP;
677     }
678 
679     /**
680      * <p>Returns {@code true} if this node is displayed and can be visible to the user
681      * (ignoring screen size, scrolling limitations, color, font-size, or overlapping nodes).</p>
682      *
683      * <p><b>NOTE:</b> If CSS is
684      * {@link org.htmlunit.WebClientOptions#setCssEnabled(boolean) disabled}, this method
685      * does <b>not</b> take this element's style into consideration!</p>
686      *
687      * @see <a href="http://www.w3.org/TR/CSS2/visufx.html#visibility">CSS2 Visibility</a>
688      * @see <a href="http://www.w3.org/TR/CSS2/visuren.html#propdef-display">CSS2 Display</a>
689      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/visibility">MDN CSS visibility</a>
690      * @return {@code true} if the node is visible to the user, {@code false} otherwise
691      * @see #mayBeDisplayed()
692      */
693     public boolean isDisplayed() {
694         if (!mayBeDisplayed()) {
695             return false;
696         }
697 
698         final Page page = getPage();
699         final WebWindow window = page.getEnclosingWindow();
700         final WebClient webClient = window.getWebClient();
701         if (webClient.getOptions().isCssEnabled()) {
702             // display: iterate top to bottom, because if a parent is display:none,
703             // there's nothing that a child can do to override it
704             final List<Node> ancestors = getAncestors();
705             final ArrayList<ComputedCssStyleDeclaration> styles = new ArrayList<>(ancestors.size());
706 
707             for (final Node node : ancestors) {
708                 if (node instanceof HtmlElement elem) {
709                     // the hidden attribute and the open state of a dialog are handled
710                     // by the computed display style (an explicit display style overrides both)
711                     final ComputedCssStyleDeclaration style = window.getComputedStyle(elem, null);
712                     if (DisplayStyle.NONE.value().equals(style.getDisplay())) {
713                         return false;
714                     }
715                     styles.add(style);
716                 }
717             }
718 
719             // visibility: iterate bottom to top, because children can override
720             // the visibility used by parent nodes
721             for (int i = styles.size() - 1; i >= 0; i--) {
722                 final ComputedCssStyleDeclaration style = styles.get(i);
723                 final String visibility = style.getStyleAttribute(StyleAttributes.Definition.VISIBILITY, true);
724                 if (visibility.length() > 5) {
725                     if ("visible".equals(visibility)) {
726                         return true;
727                     }
728                     if ("hidden".equals(visibility) || "collapse".equals(visibility)) {
729                         return false;
730                     }
731                 }
732             }
733         }
734         return true;
735     }
736 
737     /**
738      * Returns {@code true} if nodes of this type can ever be displayed, {@code false} otherwise. Examples of nodes
739      * that can never be displayed are <code>&lt;head&gt;</code>,
740      * <code>&lt;meta&gt;</code>, <code>&lt;script&gt;</code>, etc.
741      * @return {@code true} if nodes of this type can ever be displayed, {@code false} otherwise
742      * @see #isDisplayed()
743      */
744     public boolean mayBeDisplayed() {
745         return true;
746     }
747 
748     /**
749      * Returns a normalized textual representation of this element that represents
750      * what would be visible to the user if this page was shown in a web browser.
751      * Whitespace is normalized like in the browser and block tags are separated by '\n'.
752      *
753      * @return a normalized textual representation of this element
754      */
755     public String asNormalizedText() {
756         final HtmlSerializerNormalizedText ser = new HtmlSerializerNormalizedText();
757         return ser.asText(this);
758     }
759 
760     /**
761      * Returns a textual representation of this element in the same way as
762      * the selenium/WebDriver WebElement#getText() property does.<br>
763      * see <a href="https://w3c.github.io/webdriver/#get-element-text">get-element-text</a> and
764      * <a href="https://w3c.github.io/webdriver/#dfn-bot-dom-getvisibletext">dfn-bot-dom-getvisibletext</a>
765      * Note: this is different from {@link #asNormalizedText()}
766      *
767      * @return a textual representation of this element that represents what would
768      *         be visible to the user if this page was shown in a web browser
769      */
770     public String getVisibleText() {
771         final HtmlSerializerVisibleText ser = new HtmlSerializerVisibleText();
772         return ser.asText(this);
773     }
774 
775     /**
776      * Returns a string representation as XML document from this element and all it's children (recursively).<br>
777      * The charset used in the xml header is the current page encoding; but the result is still a string.
778      * You have to make sure to use the correct (in fact the same) encoding if you write this to a file.<br>
779      * This serializes the current state of the DomTree - this implies that the content of noscript tags
780      * usually serialized as string because the content is converted during parsing (if js was enabled at that time).
781      * @return the XML string
782      */
783     public String asXml() {
784         Charset charsetName = null;
785         final HtmlPage htmlPage = getHtmlPageOrNull();
786         if (htmlPage != null) {
787             charsetName = htmlPage.getCharset();
788         }
789 
790         final StringWriter stringWriter = new StringWriter();
791         try (PrintWriter printWriter = new PrintWriter(stringWriter)) {
792             boolean tag = false;
793             if (charsetName != null && this instanceof HtmlHtml) {
794                 printWriter.print("<?xml version=\"1.0\" encoding=\"");
795                 printWriter.print(charsetName);
796                 printWriter.print("\"?>");
797                 tag = true;
798             }
799             printXml("", tag, printWriter);
800             return stringWriter.toString().trim();
801         }
802     }
803 
804     /**
805      * Recursively writes the XML data for the node tree starting at <code>node</code>.
806      *
807      * @param indent white space to indent child nodes
808      * @param indentBefore if true start a new line before outputting
809      * @param printWriter writer where child nodes are written
810      * @return true if the last thing printed was a tag
811      */
812     protected boolean printXml(final String indent, final boolean indentBefore, final PrintWriter printWriter) {
813         if (indentBefore) {
814             printWriter.print("\r\n");
815             printWriter.print(indent);
816         }
817         printWriter.print(this);
818         return printChildrenAsXml(indent, false, printWriter);
819     }
820 
821     /**
822      * Recursively writes the XML data for the node tree starting at <code>node</code>.
823      *
824      * @param indent white space to indent child nodes
825      * @param tagBefore true if the last thing printed was a tag
826      * @param printWriter writer where child nodes are written
827      * @return true if the last thing printed was a tag
828      */
829     protected boolean printChildrenAsXml(final String indent, final boolean tagBefore, final PrintWriter printWriter) {
830         DomNode child = getFirstChild();
831         boolean tag = tagBefore;
832         while (child != null) {
833             tag = child.printXml(indent + "  ", tag, printWriter);
834             child = child.getNextSibling();
835         }
836         return tag;
837     }
838 
839     /**
840      * {@inheritDoc}
841      */
842     @Override
843     public String getNodeValue() {
844         return null;
845     }
846 
847     /**
848      * {@inheritDoc}
849      */
850     @Override
851     public DomNode cloneNode(final boolean deep) {
852         final DomNode newnode;
853         try {
854             newnode = (DomNode) clone();
855         }
856         catch (final CloneNotSupportedException e) {
857             throw new IllegalStateException("Clone not supported for node [" + this + "]", e);
858         }
859 
860         newnode.parent_ = null;
861         newnode.nextSibling_ = null;
862         newnode.previousSibling_ = null;
863         newnode.scriptObject_ = null;
864         newnode.firstChild_ = null;
865         newnode.attachedToPage_ = false;
866 
867         // listeners are not cloned; without this the clone would share the lists of the original
868         newnode.domListeners_ = null;
869         newnode.characterDataListeners_ = null;
870 
871         // make sure isBodyParsed() returns true
872         newnode.startLineNumber_ = -1;
873         newnode.endLineNumber_ = -1;
874 
875         // if deep, clone the children too.
876         if (deep) {
877             for (DomNode child = firstChild_; child != null; child = child.nextSibling_) {
878                 newnode.appendChild(child.cloneNode(true));
879             }
880         }
881 
882         return newnode;
883     }
884 
885     /**
886      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
887      * Returns the JavaScript object that corresponds to this node if already created; in contrast to
888      * {@link #getScriptableObject()} no new object is created.
889      *
890      * @return the JavaScript object or {@code null}
891      */
892     public HtmlUnitScriptable getScriptableObjectIfCreated() {
893         return scriptObject_;
894     }
895 
896     /**
897      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
898      *
899      * <p>Returns the JavaScript object that corresponds to this node, lazily initializing a new one if necessary.</p>
900      *
901      * <p>The logic of when and where the JavaScript object is created needs a cleanup: functions using
902      * a DOM node's JavaScript object should not have to check if they should create it first.</p>
903      *
904      * @param <T> the object type
905      * @return the JavaScript object that corresponds to this node
906      */
907     @SuppressWarnings("unchecked")
908     public <T extends HtmlUnitScriptable> T getScriptableObject() {
909         if (scriptObject_ == null) {
910             final SgmlPage page = getPage();
911             if (this == page) {
912                 final StringBuilder msg = new StringBuilder("No script object associated with the Page.");
913                 // because this is a strange case we like to provide as much info as possible
914                 msg.append(" class: '")
915                     .append(page.getClass().getName())
916                     .append('\'');
917                 try {
918                     msg.append(" url: '")
919                         .append(page.getUrl()).append("' content: ")
920                         .append(page.getWebResponse().getContentAsString());
921                 }
922                 catch (final Exception e) {
923                     // ok bad luck with detail
924                     msg.append(" no details: '").append(e).append('\'');
925                 }
926                 throw new IllegalStateException(msg.toString());
927             }
928             scriptObject_ = page.getScriptableObject().makeScriptableFor(this);
929         }
930         return (T) scriptObject_;
931     }
932 
933     /**
934      * {@inheritDoc}
935      */
936     @Override
937     public DomNode appendChild(final Node node) {
938         if (node == this) {
939             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Can not add not to itself " + this);
940         }
941         final DomNode domNode = (DomNode) node;
942         if (domNode.isAncestorOf(this)) {
943             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Can not add (grand)parent to itself " + this);
944         }
945 
946         if (domNode instanceof DomDocumentFragment fragment) {
947             for (final DomNode child : fragment.getChildren()) {
948                 appendChild(child);
949             }
950         }
951         else {
952             // clean up the new node, in case it is being moved
953             if (domNode.getParentNode() != null) {
954                 domNode.detach();
955             }
956 
957             basicAppend(domNode);
958 
959             fireAddition(domNode);
960         }
961 
962         return domNode;
963     }
964 
965     /**
966      * Appends the specified node to the end of this node's children, assuming the specified
967      * node is clean (doesn't have preexisting relationships to other nodes).
968      *
969      * @param node the node to append to this node's children
970      */
971     private void basicAppend(final DomNode node) {
972         // try to make the node setup as complete as possible
973         // before the node is reachable
974         node.setPage(getPage());
975         node.parent_ = this;
976 
977         if (firstChild_ == null) {
978             firstChild_ = node;
979         }
980         else {
981             final DomNode last = getLastChild();
982             node.previousSibling_ = last;
983             node.nextSibling_ = null; // safety first
984 
985             last.nextSibling_ = node;
986         }
987         firstChild_.previousSibling_ = node;
988     }
989 
990     /**
991      * {@inheritDoc}
992      */
993     @Override
994     public Node insertBefore(final Node newChild, final Node refChild) {
995         if (newChild instanceof DomDocumentFragment fragment) {
996             for (final DomNode child : fragment.getChildren()) {
997                 insertBefore(child, refChild);
998             }
999             return newChild;
1000         }
1001 
1002         if (refChild == null) {
1003             appendChild(newChild);
1004             return newChild;
1005         }
1006 
1007         if (refChild.getParentNode() != this) {
1008             throw new DOMException(DOMException.NOT_FOUND_ERR, "Reference node is not a child of this node.");
1009         }
1010 
1011         ((DomNode) refChild).insertBefore((DomNode) newChild);
1012         return newChild;
1013     }
1014 
1015     /**
1016      * Inserts the specified node as a new child node before this node into the child relationship this node is a
1017      * part of. If the specified node is this node, this method is a no-op.
1018      *
1019      * @param newNode the new node to insert
1020      */
1021     public void insertBefore(final DomNode newNode) {
1022         if (previousSibling_ == null) {
1023             throw new IllegalStateException("Previous sibling for " + this + " is null.");
1024         }
1025 
1026         if (newNode == this) {
1027             return;
1028         }
1029 
1030         if (newNode instanceof DomDocumentFragment) {
1031             for (final DomNode child : newNode.getChildren()) {
1032                 insertBefore(child);
1033             }
1034             return;
1035         }
1036 
1037         // clean up the new node, in case it is being moved
1038         if (newNode.getParentNode() != null) {
1039             newNode.detach();
1040         }
1041 
1042         basicInsertBefore(newNode);
1043 
1044         fireAddition(newNode);
1045     }
1046 
1047     /**
1048      * Inserts the specified node into this node's parent's children right before this node, assuming the specified
1049      * node is clean (doesn't have preexisting relationships to other nodes).
1050      *
1051      * @param node the node to insert before this node
1052      */
1053     private void basicInsertBefore(final DomNode node) {
1054         // try to make the node setup as complete as possible
1055         // before the node is reachable
1056         node.setPage(page_);
1057         node.parent_ = parent_;
1058         node.previousSibling_ = previousSibling_;
1059         node.nextSibling_ = this;
1060 
1061         if (parent_.firstChild_ == this) {
1062             parent_.firstChild_ = node;
1063         }
1064         else {
1065             previousSibling_.nextSibling_ = node;
1066         }
1067         previousSibling_ = node;
1068     }
1069 
1070     private void fireAddition(final DomNode domNode) {
1071         final boolean wasAlreadyAttached = domNode.isAttachedToPage();
1072         domNode.attachedToPage_ = isAttachedToPage();
1073 
1074         final SgmlPage page = getPage();
1075         if (domNode.attachedToPage_) {
1076             // trigger events
1077             if (null != page && page.isHtmlPage()) {
1078                 ((HtmlPage) page).notifyNodeAdded(domNode);
1079             }
1080 
1081             // a node that is already "complete" (ie not being parsed) and not yet attached
1082             if (!domNode.isBodyParsed() && !wasAlreadyAttached) {
1083                 if (domNode.getFirstChild() != null) {
1084                     for (final Iterator<DomNode> iterator =
1085                             domNode.new DescendantDomNodesIterator(); iterator.hasNext();) {
1086                         final DomNode child = iterator.next();
1087                         child.attachedToPage_ = true;
1088                         child.onAllChildrenAddedToPage(true);
1089                     }
1090                 }
1091                 domNode.onAllChildrenAddedToPage(true);
1092             }
1093         }
1094 
1095         if (this instanceof DomDocumentFragment) {
1096             onAddedToDocumentFragment();
1097         }
1098 
1099         if (page == null || page.isDomChangeListenerInUse()) {
1100             fireNodeAdded(this, domNode);
1101         }
1102     }
1103 
1104     /**
1105      * Indicates if the current node is being parsed. This means that the opening tag has already been
1106      * parsed but not the body and end tag.
1107      */
1108     private boolean isBodyParsed() {
1109         return getStartLineNumber() != -1 && getEndLineNumber() == -1;
1110     }
1111 
1112     /**
1113      * Recursively sets the new page on the node and its children.
1114      * @param newPage the new owning page
1115      */
1116     private void setPage(final SgmlPage newPage) {
1117         if (page_ == newPage) {
1118             return; // nothing to do
1119         }
1120 
1121         page_ = newPage;
1122         for (final DomNode node : getChildren()) {
1123             node.setPage(newPage);
1124         }
1125     }
1126 
1127     /**
1128      * {@inheritDoc}
1129      */
1130     @Override
1131     public Node removeChild(final Node child) {
1132         if (child.getParentNode() != this) {
1133             throw new DOMException(DOMException.NOT_FOUND_ERR, "Node is not a child of this node.");
1134         }
1135         ((DomNode) child).remove();
1136         return child;
1137     }
1138 
1139     /**
1140      * Removes all of this node's children.
1141      */
1142     public void removeAllChildren() {
1143         while (getFirstChild() != null) {
1144             getFirstChild().remove();
1145         }
1146     }
1147 
1148     /**
1149      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1150      *
1151      * Parses the specified HTML source code, appending the resulting content at the specified target location.
1152      * @param source the HTML code extract to parse
1153      * @throws IOException in case of error
1154      * @throws SAXException in case of error
1155      */
1156     public void parseHtmlSnippet(final String source) throws SAXException, IOException {
1157         final WebClient webClient = getPage().getWebClient();
1158         webClient.getPageCreator().getHtmlParser().parseFragment(webClient, this, this, source, false);
1159     }
1160 
1161     /**
1162      * Removes this node from all relationships with other nodes.
1163      */
1164     public void remove() {
1165         // same as detach for the moment
1166         detach();
1167     }
1168 
1169     /**
1170      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1171      *
1172      * Detach this node from all relationships with other nodes.
1173      * This is the first step of a move.
1174      */
1175     protected void detach() {
1176         final DomNode exParent = parent_;
1177 
1178         basicRemove();
1179 
1180         fireRemoval(exParent);
1181     }
1182 
1183     /**
1184      * Cuts off all relationships this node has with siblings and parents.
1185      */
1186     protected void basicRemove() {
1187         basicDetach();
1188 
1189         nextSibling_ = null;
1190         previousSibling_ = null;
1191         parent_ = null;
1192         attachedToPage_ = false;
1193         for (final DomNode descendant : getDescendants()) {
1194             descendant.attachedToPage_ = false;
1195         }
1196     }
1197 
1198     /**
1199      * Cuts off all relationships this node has with siblings and parents.
1200      */
1201     private void basicDetach() {
1202         if (parent_ != null && parent_.firstChild_ == this) {
1203             parent_.firstChild_ = nextSibling_;
1204         }
1205         else if (previousSibling_ != null && previousSibling_.nextSibling_ == this) {
1206             previousSibling_.nextSibling_ = nextSibling_;
1207         }
1208         if (nextSibling_ != null && nextSibling_.previousSibling_ == this) {
1209             nextSibling_.previousSibling_ = previousSibling_;
1210         }
1211         if (parent_ != null && parent_.getLastChild() == this) {
1212             parent_.firstChild_.previousSibling_ = previousSibling_;
1213         }
1214     }
1215 
1216     private void fireRemoval(final DomNode exParent) {
1217         final SgmlPage page = getPage();
1218         if (page instanceof HtmlPage htmlPage) {
1219             // some actions executed on removal need an intact parent relationship (e.g. for the
1220             // DocumentPositionComparator) so we have to restore it temporarily
1221             parent_ = exParent;
1222             htmlPage.notifyNodeRemoved(this);
1223             parent_ = null;
1224         }
1225 
1226         if (exParent != null && (page == null || page.isDomChangeListenerInUse())) {
1227             fireNodeDeleted(exParent, this);
1228             // ask ex-parent to fire event (because we don't have parent now)
1229             exParent.fireNodeDeleted(exParent, this);
1230         }
1231     }
1232 
1233     /**
1234      * {@inheritDoc}
1235      */
1236     @Override
1237     public Node replaceChild(final Node newChild, final Node oldChild) {
1238         if (oldChild.getParentNode() != this) {
1239             throw new DOMException(DOMException.NOT_FOUND_ERR, "Node is not a child of this node.");
1240         }
1241         ((DomNode) oldChild).replace((DomNode) newChild);
1242         return oldChild;
1243     }
1244 
1245     /**
1246      * Replaces this node with another node. If the specified node is this node, this
1247      * method is a no-op.
1248      * @param newNode the node to replace this one
1249      */
1250     public void replace(final DomNode newNode) {
1251         if (newNode != this) {
1252             final DomNode exParent = parent_;
1253             final DomNode exNextSibling = nextSibling_;
1254 
1255             remove();
1256 
1257             exParent.insertBefore(newNode, exNextSibling);
1258         }
1259     }
1260 
1261     /**
1262      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
1263      *
1264      * Quietly removes this node and moves its children to the specified destination. "Quietly" means
1265      * that no node events are fired. This method is not appropriate for most use cases. It should
1266      * only be used in specific cases for HTML parsing hackery.
1267      *
1268      * @param destination the node to which this node's children should be moved before this node is removed
1269      */
1270     public void quietlyRemoveAndMoveChildrenTo(final DomNode destination) {
1271         if (destination.getPage() != getPage()) {
1272             throw new RuntimeException("Cannot perform quiet move on nodes from different pages.");
1273         }
1274         for (final DomNode child : getChildren()) {
1275             if (child != destination) {
1276                 child.basicRemove();
1277                 destination.basicAppend(child);
1278             }
1279         }
1280         basicRemove();
1281     }
1282 
1283     /**
1284      * Check for insertion errors for a new child node. This is overridden by derived
1285      * classes to enforce which types of children are allowed.
1286      *
1287      * @param newChild the new child node that is being inserted below this node
1288      * @throws DOMException HIERARCHY_REQUEST_ERR: Raised if this node is of a type that does
1289      *         not allow children of the type of the newChild node, or if the node to insert is one of
1290      *         this node's ancestors or this node itself, or if this node is of type Document and the
1291      *         DOM application attempts to insert a second DocumentType or Element node.
1292      *         WRONG_DOCUMENT_ERR: Raised if newChild was created from a different document than the
1293      *         one that created this node.
1294      */
1295     protected void checkChildHierarchy(final Node newChild) throws DOMException {
1296         Node parentNode = this;
1297         while (parentNode != null) {
1298             if (parentNode == newChild) {
1299                 throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR, "Child node is already a parent.");
1300             }
1301             parentNode = parentNode.getParentNode();
1302         }
1303         final Document thisDocument = getOwnerDocument();
1304         final Document childDocument = newChild.getOwnerDocument();
1305         if (childDocument != thisDocument && childDocument != null) {
1306             throw new DOMException(DOMException.WRONG_DOCUMENT_ERR, "Child node " + newChild.getNodeName()
1307                 + " is not in the same Document as this " + getNodeName() + ".");
1308         }
1309     }
1310 
1311     /**
1312      * Lifecycle method invoked whenever a node is added to a page. Intended to
1313      * be overridden by nodes which need to perform custom logic when they are
1314      * added to a page. This method is recursive, so if you override it, please
1315      * be sure to call <code>super.onAddedToPage()</code>.
1316      */
1317     protected void onAddedToPage() {
1318         if (firstChild_ != null) {
1319             for (final DomNode child : getChildren()) {
1320                 child.onAddedToPage();
1321             }
1322         }
1323     }
1324 
1325     /**
1326      * Lifecycle method invoked after a node and all its children have been added to a page, during
1327      * parsing of the HTML. Intended to be overridden by nodes which need to perform custom logic
1328      * after they and all their child nodes have been processed by the HTML parser. This method is
1329      * not recursive, and the default implementation is empty, so there is no need to call
1330      * <code>super.onAllChildrenAddedToPage()</code> if you implement this method.
1331      * @param postponed whether to use {@link org.htmlunit.javascript.PostponedAction} or no
1332      */
1333     public void onAllChildrenAddedToPage(final boolean postponed) {
1334         // Empty by default.
1335     }
1336 
1337     /**
1338      * Lifecycle method invoked whenever a node is added to a document fragment. Intended to
1339      * be overridden by nodes which need to perform custom logic when they are
1340      * added to a fragment. This method is recursive, so if you override it, please
1341      * be sure to call <code>super.onAddedToDocumentFragment()</code>.
1342      */
1343     protected void onAddedToDocumentFragment() {
1344         if (firstChild_ != null) {
1345             for (final DomNode child : getChildren()) {
1346                 child.onAddedToDocumentFragment();
1347             }
1348         }
1349     }
1350 
1351     /**
1352      * Add a DOM node as a child to this node before the referenced node.
1353      * If the referenced node is null, append to the end.
1354      * @param movedDomNode the node to move
1355      * @param referenceDomNode the node to move before
1356      * @throws DOMException in case of problems
1357      */
1358     public void moveBefore(final DomNode movedDomNode, final DomNode referenceDomNode) {
1359         if (movedDomNode == referenceDomNode) {
1360             return;
1361         }
1362 
1363         if (movedDomNode instanceof DomDocumentFragment fragment) {
1364             for (final DomNode child : fragment.getChildren()) {
1365                 moveBefore(child, referenceDomNode);
1366             }
1367             return;
1368         }
1369 
1370         // If moving to the same position (node is already right before referenceNode), no operation needed
1371         if (referenceDomNode != null && movedDomNode.getNextSibling() == referenceDomNode) {
1372             return;
1373         }
1374 
1375         if (movedDomNode.isAncestorOf(this)) {
1376             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
1377                     "The new child element contains the parent.");
1378         }
1379 
1380         if (referenceDomNode != null && !this.isAncestorOf(referenceDomNode)) {
1381             throw new DOMException(DOMException.NOT_FOUND_ERR,
1382                     "The node before which the new node is to be inserted is not a child of this node.");
1383         }
1384 
1385         if (referenceDomNode != null && referenceDomNode.isAttachedToPage() && !movedDomNode.isAttachedToPage()) {
1386             throw new DOMException(DOMException.HIERARCHY_REQUEST_ERR,
1387                     "State-preserving atomic move cannot be performed on nodes participating in an invalid hierarchy.");
1388         }
1389 
1390         if (referenceDomNode == null) {
1391             appendChild(movedDomNode);
1392             return;
1393         }
1394 
1395         referenceDomNode.moveBefore(movedDomNode);
1396     }
1397 
1398     /**
1399      * Inserts the specified node as a new child node before this node into the child relationship this node is a
1400      * part of. If the specified node is this node, this method is a no-op.
1401      *
1402      * @param movedDomNode the node to move before the current node
1403      */
1404     public void moveBefore(final DomNode movedDomNode) {
1405         if (previousSibling_ == null) {
1406             throw new IllegalStateException("Previous sibling for " + this + " is null.");
1407         }
1408 
1409         if (movedDomNode == this) {
1410             return;
1411         }
1412 
1413         movedDomNode.detach();
1414         basicInsertBefore(movedDomNode);
1415 
1416         fireAddition(movedDomNode);
1417     }
1418 
1419     /**
1420      * Returns an iterable over the children of this node.
1421      *
1422      * @return an {@link Iterable} over the children of this node
1423      */
1424     public final Iterable<DomNode> getChildren() {
1425         return () -> new ChildIterator(firstChild_);
1426     }
1427 
1428     /**
1429      * An iterator over all children of this node.
1430      */
1431     protected static class ChildIterator implements Iterator<DomNode> {
1432 
1433         private DomNode nextNode_;
1434         private DomNode currentNode_;
1435 
1436         public ChildIterator(final DomNode nextNode) {
1437             nextNode_ = nextNode;
1438         }
1439 
1440         /** {@inheritDoc} */
1441         @Override
1442         public boolean hasNext() {
1443             return nextNode_ != null;
1444         }
1445 
1446         /** {@inheritDoc} */
1447         @Override
1448         public DomNode next() {
1449             if (nextNode_ != null) {
1450                 currentNode_ = nextNode_;
1451                 nextNode_ = nextNode_.nextSibling_;
1452                 return currentNode_;
1453             }
1454             throw new NoSuchElementException();
1455         }
1456 
1457         /** {@inheritDoc} */
1458         @Override
1459         public void remove() {
1460             if (currentNode_ == null) {
1461                 throw new IllegalStateException();
1462             }
1463             currentNode_.remove();
1464         }
1465     }
1466 
1467     /**
1468      * Returns an {@link Iterable} that will recursively iterate over all of this node's descendants,
1469      * including {@link DomText} elements, {@link DomComment} elements, etc. If you want to iterate
1470      * only over {@link HtmlElement} descendants, please use {@link #getHtmlElementDescendants()}.
1471      * @return an {@link Iterable} that will recursively iterate over all of this node's descendants
1472      */
1473     public final Iterable<DomNode> getDescendants() {
1474         return () -> new DescendantDomNodesIterator();
1475     }
1476 
1477     /**
1478      * Returns an {@link Iterable} that will recursively iterate over all of this node's {@link HtmlElement}
1479      * descendants. If you want to iterate over all descendants (including {@link DomText} elements,
1480      * {@link DomComment} elements, etc.), please use {@link #getDescendants()}.
1481      * @return an {@link Iterable} that will recursively iterate over all of this node's {@link HtmlElement}
1482      *         descendants
1483      * @see #getDomElementDescendants()
1484      */
1485     public final Iterable<HtmlElement> getHtmlElementDescendants() {
1486         return () -> new DescendantHtmlElementsIterator();
1487     }
1488 
1489     /**
1490      * Returns an {@link Iterable} that will recursively iterate over all of this node's {@link DomElement}
1491      * descendants. If you want to iterate over all descendants (including {@link DomText} elements,
1492      * {@link DomComment} elements, etc.), please use {@link #getDescendants()}.
1493      * @return an {@link Iterable} that will recursively iterate over all of this node's {@link DomElement}
1494      *         descendants
1495      * @see #getHtmlElementDescendants()
1496      */
1497     public final Iterable<DomElement> getDomElementDescendants() {
1498         return () -> new DescendantDomElementsIterator();
1499     }
1500 
1501     /**
1502      * Iterates over all descendants DomNodes, in document order.
1503      */
1504     protected final class DescendantDomNodesIterator implements Iterator<DomNode> {
1505         private DomNode currentNode_;
1506         private DomNode nextNode_;
1507 
1508         /**
1509          * Creates a new instance which iterates over the specified node type.
1510          */
1511         public DescendantDomNodesIterator() {
1512             nextNode_ = DomNode.this.getFirstChild();
1513         }
1514 
1515         /** {@inheritDoc} */
1516         @Override
1517         public boolean hasNext() {
1518             return nextNode_ != null;
1519         }
1520 
1521         /** {@inheritDoc} */
1522         @Override
1523         public DomNode next() {
1524             return nextNode();
1525         }
1526 
1527         /** {@inheritDoc} */
1528         @Override
1529         public void remove() {
1530             if (currentNode_ == null) {
1531                 throw new IllegalStateException("Unable to remove current node, because there is no current node.");
1532             }
1533             final DomNode current = currentNode_;
1534             while (nextNode_ != null && current.isAncestorOf(nextNode_)) {
1535                 next();
1536             }
1537             current.remove();
1538         }
1539 
1540         /**
1541          * Returns the next node in the iteration.
1542          *
1543          * @return the next node, or {@code null} if there are no more nodes
1544          */
1545         public DomNode nextNode() {
1546             currentNode_ = nextNode_;
1547 
1548             DomNode next = nextNode_.getFirstChild();
1549             if (next == null) {
1550                 next = nextNode_.getNextSibling();
1551             }
1552             if (next == null) {
1553                 next = getNextElementUpwards(nextNode_);
1554             }
1555             nextNode_ = next;
1556 
1557             return currentNode_;
1558         }
1559 
1560         private DomNode getNextElementUpwards(final DomNode startingNode) {
1561             if (startingNode == DomNode.this) {
1562                 return null;
1563             }
1564 
1565             DomNode parent = startingNode.getParentNode();
1566             while (parent != null && parent != DomNode.this) {
1567                 final DomNode next = parent.getNextSibling();
1568                 if (next != null) {
1569                     return next;
1570                 }
1571                 parent = parent.getParentNode();
1572             }
1573             return null;
1574         }
1575     }
1576 
1577     /**
1578      * Iterates over all descendants DomElements, in document order.
1579      *
1580      * @param <T> the element type
1581      */
1582     protected abstract class AbstractDescendantIterator<T extends DomNode> implements Iterator<T> {
1583         private DomNode currentNode_;
1584         private DomNode nextNode_;
1585 
1586         /**
1587          * Creates a new instance which iterates over the specified node type.
1588          */
1589         protected AbstractDescendantIterator() {
1590             nextNode_ = getFirstChildElement(DomNode.this);
1591         }
1592 
1593         /** {@inheritDoc} */
1594         @Override
1595         public boolean hasNext() {
1596             return nextNode_ != null;
1597         }
1598 
1599         /** {@inheritDoc} */
1600         @Override
1601         public T next() {
1602             return nextNode();
1603         }
1604 
1605         /** {@inheritDoc} */
1606         @Override
1607         public void remove() {
1608             if (currentNode_ == null) {
1609                 throw new IllegalStateException("Unable to remove current node, because there is no current node.");
1610             }
1611             final DomNode current = currentNode_;
1612             while (nextNode_ != null && current.isAncestorOf(nextNode_)) {
1613                 next();
1614             }
1615             current.remove();
1616         }
1617 
1618         /**
1619          * Returns the next node in the iteration.
1620          *
1621          * @return the next node, or {@code null} if there are no more nodes
1622          */
1623         @SuppressWarnings("unchecked")
1624         public T nextNode() {
1625             currentNode_ = nextNode_;
1626 
1627             DomNode next = getFirstChildElement(nextNode_);
1628             if (next == null) {
1629                 next = getNextDomSibling(nextNode_);
1630             }
1631             if (next == null) {
1632                 next = getNextElementUpwards(nextNode_);
1633             }
1634             nextNode_ = next;
1635 
1636             return (T) currentNode_;
1637         }
1638 
1639         private DomNode getNextElementUpwards(final DomNode startingNode) {
1640             if (startingNode == DomNode.this) {
1641                 return null;
1642             }
1643 
1644             DomNode parent = startingNode.getParentNode();
1645             while (parent != null && parent != DomNode.this) {
1646                 DomNode next = parent.getNextSibling();
1647                 while (next != null && !isAccepted(next)) {
1648                     next = next.getNextSibling();
1649                 }
1650                 if (next != null) {
1651                     return next;
1652                 }
1653                 parent = parent.getParentNode();
1654             }
1655             return null;
1656         }
1657 
1658         private DomNode getFirstChildElement(final DomNode parent) {
1659             DomNode node = parent.getFirstChild();
1660             while (node != null && !isAccepted(node)) {
1661                 node = node.getNextSibling();
1662             }
1663             return node;
1664         }
1665 
1666         /**
1667          * Indicates if the node is accepted. If not it won't be explored at all.
1668          *
1669          * @param node the node to test
1670          * @return {@code true} if accepted
1671          */
1672         protected abstract boolean isAccepted(DomNode node);
1673 
1674         private DomNode getNextDomSibling(final DomNode element) {
1675             DomNode node = element.getNextSibling();
1676             while (node != null && !isAccepted(node)) {
1677                 node = node.getNextSibling();
1678             }
1679             return node;
1680         }
1681     }
1682 
1683     /**
1684      * Iterates over all descendants DomTypes, in document order.
1685      */
1686     protected final class DescendantDomElementsIterator extends AbstractDescendantIterator<DomElement> {
1687         /**
1688          * {@inheritDoc}
1689          */
1690         @Override
1691         protected boolean isAccepted(final DomNode node) {
1692             return node instanceof DomElement;
1693         }
1694     }
1695 
1696     /**
1697      * Iterates over all descendants DomTypes, in document order.
1698      */
1699     protected final class DescendantHtmlElementsIterator extends AbstractDescendantIterator<HtmlElement> {
1700         /**
1701          * {@inheritDoc}
1702          */
1703         @Override
1704         protected boolean isAccepted(final DomNode node) {
1705             return node instanceof HtmlElement;
1706         }
1707     }
1708 
1709     /**
1710      * Returns this node's ready state (IE only).
1711      * @return this node's ready state
1712      */
1713     public String getReadyState() {
1714         return readyState_;
1715     }
1716 
1717     /**
1718      * Sets this node's ready state (IE only).
1719      * @param state this node's ready state
1720      */
1721     public void setReadyState(final String state) {
1722         readyState_ = state;
1723     }
1724 
1725     /**
1726      * Evaluates the specified XPath expression from this node, returning the matching elements.
1727      * <br>
1728      * Note: This implies that the ',' point to this node but the general axis like '//' are still
1729      * looking at the whole document. E.g. if you like to get all child h1 nodes from the current one
1730      * you have to use './/h1' instead of '//h1' because the latter matches all h1 nodes of the#
1731      * whole document.
1732      *
1733      * @param <T> the expected type
1734      * @param xpathExpr the XPath expression to evaluate
1735      * @return the elements which match the specified XPath expression
1736      * @see #getFirstByXPath(String)
1737      * @see #getCanonicalXPath()
1738      */
1739     public <T> List<T> getByXPath(final String xpathExpr) {
1740         return XPathHelper.getByXPath(this, xpathExpr, null);
1741     }
1742 
1743     /**
1744      * Evaluates the specified XPath expression from this node, returning the matching elements.
1745      *
1746      * @param xpathExpr the XPath expression to evaluate
1747      * @param resolver the prefix resolver to use for resolving namespace prefixes, or null
1748      * @return the elements which match the specified XPath expression
1749      * @see #getFirstByXPath(String)
1750      * @see #getCanonicalXPath()
1751      */
1752     public List<?> getByXPath(final String xpathExpr, final PrefixResolver resolver) {
1753         return XPathHelper.getByXPath(this, xpathExpr, resolver);
1754     }
1755 
1756     /**
1757      * Evaluates the specified XPath expression from this node, returning the first matching element,
1758      * or {@code null} if no node matches the specified XPath expression.
1759      *
1760      * @param xpathExpr the XPath expression
1761      * @param <X> the expression type
1762      * @return the first element matching the specified XPath expression
1763      * @see #getByXPath(String)
1764      * @see #getCanonicalXPath()
1765      */
1766     public <X> X getFirstByXPath(final String xpathExpr) {
1767         return getFirstByXPath(xpathExpr, null);
1768     }
1769 
1770     /**
1771      * Evaluates the specified XPath expression from this node, returning the first matching element,
1772      * or {@code null} if no node matches the specified XPath expression.
1773      *
1774      * @param xpathExpr the XPath expression
1775      * @param <X> the expression type
1776      * @param resolver the prefix resolver to use for resolving namespace prefixes, or null
1777      * @return the first element matching the specified XPath expression
1778      * @see #getByXPath(String)
1779      * @see #getCanonicalXPath()
1780      */
1781     @SuppressWarnings("unchecked")
1782     public <X> X getFirstByXPath(final String xpathExpr, final PrefixResolver resolver) {
1783         final List<?> results = getByXPath(xpathExpr, resolver);
1784         if (results.isEmpty()) {
1785             return null;
1786         }
1787         return (X) results.get(0);
1788     }
1789 
1790     /**
1791      * <p>Returns the canonical XPath expression which identifies this node, for instance
1792      * <code>"/html/body/table[3]/tbody/tr[5]/td[2]/span/a[3]"</code>.</p>
1793      *
1794      * <p><span style="color:red">WARNING:</span> This sort of automated XPath expression
1795      * is often quite bad at identifying a node, as it is highly sensitive to changes in
1796      * the DOM tree.</p>
1797      *
1798      * @return the canonical XPath expression which identifies this node
1799      * @see #getByXPath(String)
1800      */
1801     public String getCanonicalXPath() {
1802         throw new RuntimeException("Method getCanonicalXPath() not implemented for nodes of type " + getNodeType());
1803     }
1804 
1805     /**
1806      * Notifies the registered {@link IncorrectnessListener} of something that is not fully correct.
1807      * @param message the notification to send to the registered {@link IncorrectnessListener}
1808      */
1809     protected void notifyIncorrectness(final String message) {
1810         final WebClient client = getPage().getEnclosingWindow().getWebClient();
1811         final IncorrectnessListener incorrectnessListener = client.getIncorrectnessListener();
1812         incorrectnessListener.notify(message, this);
1813     }
1814 
1815     /**
1816      * Adds a {@link DomChangeListener} to the listener list. The listener is registered for
1817      * all descendants of this node.
1818      *
1819      * @param listener the DOM structure change listener to be added
1820      * @see #removeDomChangeListener(DomChangeListener)
1821      */
1822     public void addDomChangeListener(final DomChangeListener listener) {
1823         WebAssert.notNull("listener", listener);
1824 
1825         synchronized (this) {
1826             if (domListeners_ == null) {
1827                 domListeners_ = new CopyOnWriteArrayList<>();
1828             }
1829             domListeners_.add(listener);
1830 
1831             final SgmlPage page = getPage();
1832             if (page != null) {
1833                 page.domChangeListenerAdded();
1834             }
1835         }
1836     }
1837 
1838     /**
1839      * Removes a {@link DomChangeListener} from the listener list. The listener is deregistered for
1840      * all descendants of this node.
1841      *
1842      * @param listener the DOM structure change listener to be removed
1843      * @see #addDomChangeListener(DomChangeListener)
1844      */
1845     public void removeDomChangeListener(final DomChangeListener listener) {
1846         WebAssert.notNull("listener", listener);
1847 
1848         final List<DomChangeListener> listeners = domListeners_;
1849         if (listeners != null) {
1850             listeners.remove(listener);
1851         }
1852     }
1853 
1854     /**
1855      * Support for reporting DOM changes. This method can be called when a node has been added, and it
1856      * will send the appropriate {@link DomChangeEvent} to any registered {@link DomChangeListener}s.
1857      *
1858      * <p>Note that this method recursively calls this node's parent's {@link #fireNodeAdded(DomNode, DomNode)}.</p>
1859      *
1860      * @param parentNode the parent of the node that was changed
1861      * @param addedNode the node that has been added
1862      */
1863     protected void fireNodeAdded(final DomNode parentNode, final DomNode addedNode) {
1864         DomChangeEvent event = null;
1865 
1866         DomNode toInform = this;
1867         while (toInform != null) {
1868             final List<DomChangeListener> listeners = toInform.domListeners_;
1869             if (listeners != null && !listeners.isEmpty()) {
1870                 if (event == null) {
1871                     event = new DomChangeEvent(parentNode, addedNode);
1872                 }
1873                 for (final DomChangeListener domChangeListener : listeners) {
1874                     domChangeListener.nodeAdded(event);
1875                 }
1876             }
1877 
1878             toInform = toInform.getParentNode();
1879         }
1880     }
1881 
1882     /**
1883      * Adds a {@link CharacterDataChangeListener} to the listener list. The listener is registered for
1884      * all descendants of this node.
1885      *
1886      * @param listener the character data change listener to be added
1887      * @see #removeCharacterDataChangeListener(CharacterDataChangeListener)
1888      */
1889     public void addCharacterDataChangeListener(final CharacterDataChangeListener listener) {
1890         WebAssert.notNull("listener", listener);
1891 
1892         synchronized (this) {
1893             if (characterDataListeners_ == null) {
1894                 characterDataListeners_ = new CopyOnWriteArrayList<>();
1895             }
1896             characterDataListeners_.add(listener);
1897 
1898             final SgmlPage page = getPage();
1899             if (page != null) {
1900                 page.characterDataChangeListenerAdded();
1901             }
1902         }
1903     }
1904 
1905     /**
1906      * Removes a {@link CharacterDataChangeListener} from the listener list. The listener is deregistered for
1907      * all descendants of this node.
1908      *
1909      * @param listener the Character Data change listener to be removed
1910      * @see #addCharacterDataChangeListener(CharacterDataChangeListener)
1911      */
1912     public void removeCharacterDataChangeListener(final CharacterDataChangeListener listener) {
1913         WebAssert.notNull("listener", listener);
1914 
1915         final List<CharacterDataChangeListener> listeners = characterDataListeners_;
1916         if (listeners != null) {
1917             listeners.remove(listener);
1918         }
1919     }
1920 
1921     /**
1922      * Support for reporting Character Data changes.
1923      *
1924      * <p>Note that this method recursively calls this node's parent's {@link #fireCharacterDataChanged}.</p>
1925      *
1926      * @param characterData the character data which is changed
1927      * @param oldValue the old value
1928      */
1929     protected void fireCharacterDataChanged(final DomCharacterData characterData, final String oldValue) {
1930         CharacterDataChangeEvent event = null;
1931 
1932         DomNode toInform = this;
1933         while (toInform != null) {
1934             final List<CharacterDataChangeListener> listeners = toInform.characterDataListeners_;
1935             if (listeners != null && !listeners.isEmpty()) {
1936                 if (event == null) {
1937                     event = new CharacterDataChangeEvent(characterData, oldValue);
1938                 }
1939                 for (final CharacterDataChangeListener domChangeListener : listeners) {
1940                     domChangeListener.characterDataChanged(event);
1941                 }
1942             }
1943 
1944             toInform = toInform.getParentNode();
1945         }
1946     }
1947 
1948     /**
1949      * Support for reporting DOM changes. This method can be called when a node has been deleted, and it
1950      * will send the appropriate {@link DomChangeEvent} to any registered {@link DomChangeListener}s.
1951      *
1952      * <p>Note that this method recursively calls this node's parent's {@link #fireNodeDeleted(DomNode, DomNode)}.</p>
1953      *
1954      * @param parentNode the parent of the node that was changed
1955      * @param deletedNode the node that has been deleted
1956      */
1957     protected void fireNodeDeleted(final DomNode parentNode, final DomNode deletedNode) {
1958         DomChangeEvent event = null;
1959 
1960         DomNode toInform = this;
1961         while (toInform != null) {
1962             final List<DomChangeListener> listeners = toInform.domListeners_;
1963             if (listeners != null && !listeners.isEmpty()) {
1964                 if (event == null) {
1965                     event = new DomChangeEvent(parentNode, deletedNode);
1966                 }
1967                 for (final DomChangeListener domChangeListener : listeners) {
1968                     domChangeListener.nodeDeleted(event);
1969                 }
1970             }
1971 
1972             toInform = toInform.getParentNode();
1973         }
1974     }
1975 
1976     /**
1977      * Retrieves all element nodes from descendants of the starting element node that match any selector
1978      * within the supplied selector strings.
1979      * Like {@code element.querySelectorAll()} in the browsers, this node is the scope ({@code :scope}).
1980      * @param selectors one or more CSS selectors separated by commas
1981      * @return list of all found nodes
1982      */
1983     public DomNodeList<DomNode> querySelectorAll(final String selectors) {
1984         return querySelectorAll(selectors, this);
1985     }
1986 
1987     /**
1988      * Retrieves all element nodes from descendants of the starting element node that match any selector
1989      * within the supplied selector strings.
1990      * @param selectors one or more CSS selectors separated by commas
1991      * @param scope the context scope node used for evaluating relative selectors like :scope
1992      * @return list of all found nodes
1993      */
1994     public DomNodeList<DomNode> querySelectorAll(final String selectors, final DomNode scope) {
1995         try {
1996             final WebClient webClient = getPage().getWebClient();
1997             final SelectorList selectorList = getSelectorList(selectors, webClient);
1998 
1999             final List<DomNode> elements = new ArrayList<>();
2000             if (selectorList != null) {
2001                 for (final DomElement child : getDomElementDescendants()) {
2002                     for (final Selector selector : selectorList) {
2003                         if (CssStyleSheet.selects(webClient.getBrowserVersion(), child,
2004                                 selector, null, scope, true, true)) {
2005                             elements.add(child);
2006                             break;
2007                         }
2008                     }
2009                 }
2010             }
2011             return new StaticDomNodeList(elements);
2012         }
2013         catch (final IOException e) {
2014             throw new CSSException("Error parsing CSS selectors from '" + selectors + "': " + e.getMessage(), e);
2015         }
2016     }
2017 
2018     /**
2019      * Returns the {@link SelectorList}.
2020      * @param selectors the selectors
2021      * @param webClient the {@link WebClient}
2022      * @return the {@link SelectorList}
2023      * @throws IOException if an error occurs
2024      */
2025     protected SelectorList getSelectorList(final String selectors, final WebClient webClient)
2026             throws IOException {
2027 
2028         // get us a CSS3Parser from the pool so the chance of reusing it are high
2029         try (PooledCSS3Parser pooledParser = webClient.getCSS3Parser()) {
2030             final CSSOMParser parser = new CSSOMParser(pooledParser);
2031             final CheckErrorHandler errorHandler = new CheckErrorHandler();
2032             parser.setErrorHandler(errorHandler);
2033 
2034             final SelectorList selectorList = parser.parseSelectors(selectors);
2035             // in case of error parseSelectors returns null
2036             if (errorHandler.error() != null) {
2037                 throw new CSSException("Invalid selectors: '" + selectors + "'", errorHandler.error());
2038             }
2039 
2040             if (selectorList != null) {
2041                 CssStyleSheet.validateSelectors(selectorList, this);
2042 
2043             }
2044             return selectorList;
2045         }
2046     }
2047 
2048     /**
2049      * Returns the first element within the document that matches the specified group of selectors.
2050      * Like {@code element.querySelector()} in the browsers, this node is the scope ({@code :scope}).
2051      * @param selectors one or more CSS selectors separated by commas
2052      * @param <N> the node type
2053      * @return null if no matches are found; otherwise, it returns the first matching element
2054      */
2055     public <N extends DomNode> N querySelector(final String selectors) {
2056         return querySelector(selectors, this);
2057     }
2058 
2059     /**
2060      * Returns the first element within the document that matches the specified group of selectors.
2061      * @param selectors one or more CSS selectors separated by commas
2062      * @param scope the context scope node used for evaluating relative selectors like :scope
2063      * @param <N> the node type
2064      * @return null if no matches are found; otherwise, it returns the first matching element
2065      */
2066     @SuppressWarnings("unchecked")
2067     public <N extends DomNode> N querySelector(final String selectors, final DomNode scope) {
2068         final DomNodeList<DomNode> list = querySelectorAll(selectors, scope);
2069         if (!list.isEmpty()) {
2070             return (N) list.get(0);
2071         }
2072         return null;
2073     }
2074 
2075     /**
2076      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2077      *
2078      * Indicates if this node is currently attached to the page.
2079      * @return {@code true} if the page is one ancestor of the node.
2080      */
2081     public boolean isAttachedToPage() {
2082         return attachedToPage_;
2083     }
2084 
2085     /**
2086      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2087      *
2088      * Lifecycle method to support special processing for js method importNode.
2089      * @param doc the import target document
2090      * @see org.htmlunit.javascript.host.dom.Document#importNode(
2091      * org.htmlunit.javascript.host.dom.Node, boolean)
2092      * @see HtmlScript#processImportNode(org.htmlunit.javascript.host.dom.Document)
2093      */
2094     public void processImportNode(final org.htmlunit.javascript.host.dom.Document doc) {
2095         page_ = (SgmlPage) doc.getDomNodeOrDie();
2096     }
2097 
2098     /**
2099      * <span style="color:red">INTERNAL API - SUBJECT TO CHANGE AT ANY TIME - USE AT YOUR OWN RISK.</span><br>
2100      *
2101      * Helper for a common call sequence.
2102      * @param feature the feature to check
2103      * @return {@code true} if the currently emulated browser has this feature.
2104      */
2105     public boolean hasFeature(final BrowserVersionFeatures feature) {
2106         return getPage().getWebClient().getBrowserVersion().hasFeature(feature);
2107     }
2108 
2109     private static final class CheckErrorHandler implements CSSErrorHandler {
2110         private CSSParseException error_;
2111 
2112         CSSParseException error() {
2113             return error_;
2114         }
2115 
2116         @Override
2117         public void warning(final CSSParseException exception) throws CSSException {
2118             // ignore
2119         }
2120 
2121         @Override
2122         public void fatalError(final CSSParseException exception) throws CSSException {
2123             error_ = exception;
2124         }
2125 
2126         @Override
2127         public void error(final CSSParseException exception) throws CSSException {
2128             error_ = exception;
2129         }
2130     }
2131 
2132     /**
2133      * Indicates if the provided event can be applied to this node.
2134      * Overwrite this.
2135      * @param event the event
2136      * @return {@code false} if the event can't be applied
2137      */
2138     public boolean handles(final Event event) {
2139         return true;
2140     }
2141 
2142     /**
2143      * Returns the previous sibling element node of this element.
2144      * null if this element has no element sibling nodes that come before this one in the document tree.
2145      * @return the previous sibling element node of this element.
2146      *         null if this element has no element sibling nodes that come before this one in the document tree
2147      */
2148     public DomElement getPreviousElementSibling() {
2149         DomNode node = getPreviousSibling();
2150         for ( ; node != null; node = node.getPreviousSibling()) {
2151             if (node instanceof DomElement elem) {
2152                 return elem;
2153             }
2154         }
2155         return null;
2156     }
2157 
2158     /**
2159      * Returns the next sibling element node of this element.
2160      * null if this element has no element sibling nodes that come after this one in the document tree.
2161      * @return the next sibling element node of this element.
2162      *         null if this element has no element sibling nodes that come after this one in the document tree
2163      */
2164     public DomElement getNextElementSibling() {
2165         DomNode node = getNextSibling();
2166         for ( ; node != null; node = node.getNextSibling()) {
2167             if (node instanceof DomElement elem) {
2168                 return elem;
2169             }
2170         }
2171         return null;
2172     }
2173 
2174     /**
2175      * Returns the closest ancestor element, or this element, that matches the
2176      * specified CSS selector.
2177      *
2178      * @param selectorString the CSS selector to test
2179      * @return the closest matching {@link DomElement}, or {@code null} if no
2180      *         matching element is found
2181      */
2182     public DomElement closest(final String selectorString) {
2183         try {
2184             final WebClient webClient = getPage().getWebClient();
2185             final SelectorList selectorList = getSelectorList(selectorString, webClient);
2186 
2187             if (selectorList != null) {
2188                 // closest() only ever matches elements; if this node isn't one,
2189                 // start the search from the nearest ancestor element instead.
2190                 DomNode current = this;
2191                 for ( ; current != null; current = current.getParentNode()) {
2192                     if (current instanceof DomElement elem) {
2193                         for (final Selector selector : selectorList) {
2194                             if (CssStyleSheet.selects(
2195                                     webClient.getBrowserVersion(), elem, selector, null, this, true, true)) {
2196                                 return elem;
2197                             }
2198                         }
2199                     }
2200                 }
2201             }
2202             return null;
2203         }
2204         catch (final IOException e) {
2205             throw new CSSException("Error parsing CSS selectors from '" + selectorString + "': " + e.getMessage(), e);
2206         }
2207     }
2208 
2209     /**
2210      * An unmodifiable empty {@link NamedNodeMap} implementation.
2211      */
2212     private static final class ReadOnlyEmptyNamedNodeMapImpl implements NamedNodeMap, Serializable {
2213 
2214         /**
2215          * {@inheritDoc}
2216          */
2217         @Override
2218         public int getLength() {
2219             return 0;
2220         }
2221 
2222         /**
2223          * {@inheritDoc}
2224          */
2225         @Override
2226         public DomAttr getNamedItem(final String name) {
2227             return null;
2228         }
2229 
2230         /**
2231          * {@inheritDoc}
2232          */
2233         @Override
2234         public Node getNamedItemNS(final String namespaceURI, final String localName) {
2235             return null;
2236         }
2237 
2238         /**
2239          * {@inheritDoc}
2240          */
2241         @Override
2242         public Node item(final int index) {
2243             return null;
2244         }
2245 
2246         /**
2247          * {@inheritDoc}
2248          */
2249         @Override
2250         public Node removeNamedItem(final String name) throws DOMException {
2251             return null;
2252         }
2253 
2254         /**
2255          * {@inheritDoc}
2256          */
2257         @Override
2258         public Node removeNamedItemNS(final String namespaceURI, final String localName) {
2259             return null;
2260         }
2261 
2262         /**
2263          * {@inheritDoc}
2264          */
2265         @Override
2266         public DomAttr setNamedItem(final Node node) {
2267             throw new UnsupportedOperationException("ReadOnlyEmptyNamedAttrNodeMapImpl.setNamedItem");
2268         }
2269 
2270         /**
2271          * {@inheritDoc}
2272          */
2273         @Override
2274         public Node setNamedItemNS(final Node node) throws DOMException {
2275             throw new UnsupportedOperationException("ReadOnlyEmptyNamedAttrNodeMapImpl.setNamedItemNS");
2276         }
2277     }
2278 }