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.javascript.host.dom;
16  
17  import java.io.Serializable;
18  import java.util.ArrayList;
19  import java.util.HashMap;
20  import java.util.List;
21  import java.util.Map;
22  import java.util.Objects;
23  import java.util.function.Supplier;
24  
25  import org.htmlunit.SgmlPage;
26  import org.htmlunit.corejs.javascript.Context;
27  import org.htmlunit.corejs.javascript.Function;
28  import org.htmlunit.corejs.javascript.Scriptable;
29  import org.htmlunit.corejs.javascript.VarScope;
30  import org.htmlunit.html.DomDocumentFragment;
31  import org.htmlunit.html.DomElement;
32  import org.htmlunit.html.DomNode;
33  import org.htmlunit.html.HtmlElement;
34  import org.htmlunit.html.HtmlInlineFrame;
35  import org.htmlunit.javascript.HtmlUnitScriptable;
36  import org.htmlunit.javascript.JavaScriptEngine;
37  import org.htmlunit.javascript.configuration.JsxClass;
38  import org.htmlunit.javascript.configuration.JsxConstant;
39  import org.htmlunit.javascript.configuration.JsxConstructor;
40  import org.htmlunit.javascript.configuration.JsxFunction;
41  import org.htmlunit.javascript.configuration.JsxGetter;
42  import org.htmlunit.javascript.configuration.JsxSetter;
43  import org.htmlunit.javascript.host.Element;
44  import org.htmlunit.javascript.host.NamedNodeMap;
45  import org.htmlunit.javascript.host.event.EventTarget;
46  import org.htmlunit.javascript.host.html.HTMLCollection;
47  import org.htmlunit.javascript.host.html.HTMLDocument;
48  import org.htmlunit.javascript.host.html.HTMLHtmlElement;
49  
50  /**
51   * The JavaScript object {@code Node} which is the base class for all DOM
52   * objects. This will typically wrap an instance of {@link DomNode}.
53   *
54   * @author Mike Bowler
55   * @author David K. Taylor
56   * @author Barnaby Court
57   * @author Christian Sell
58   * @author George Murnock
59   * @author Chris Erskine
60   * @author Bruce Faulkner
61   * @author Ahmed Ashour
62   * @author Ronald Brill
63   * @author Frank Danek
64   */
65  @JsxClass
66  public class Node extends EventTarget {
67  
68      /**
69       * The node is an element.
70       *
71       * @see org.w3c.dom.Node#ELEMENT_NODE
72       */
73      @JsxConstant
74      public static final int ELEMENT_NODE = org.w3c.dom.Node.ELEMENT_NODE;
75  
76      /**
77       * The node is an attribute.
78       *
79       * @see org.w3c.dom.Node#ATTRIBUTE_NODE
80       */
81      @JsxConstant
82      public static final int ATTRIBUTE_NODE = org.w3c.dom.Node.ATTRIBUTE_NODE;
83  
84      /**
85       * The node is a text node.
86       *
87       * @see org.w3c.dom.Node#TEXT_NODE
88       */
89      @JsxConstant
90      public static final int TEXT_NODE = org.w3c.dom.Node.TEXT_NODE;
91  
92      /**
93       * The node is a CDATA section.
94       *
95       * @see org.w3c.dom.Node#CDATA_SECTION_NODE
96       */
97      @JsxConstant
98      public static final int CDATA_SECTION_NODE = org.w3c.dom.Node.CDATA_SECTION_NODE;
99  
100     /**
101      * The node is an entity reference.
102      *
103      * @see org.w3c.dom.Node#ENTITY_REFERENCE_NODE
104      */
105     @JsxConstant
106     public static final int ENTITY_REFERENCE_NODE = org.w3c.dom.Node.ENTITY_REFERENCE_NODE;
107 
108     /**
109      * The node is an entity.
110      *
111      * @see org.w3c.dom.Node#ENTITY_NODE
112      */
113     @JsxConstant
114     public static final int ENTITY_NODE = org.w3c.dom.Node.ENTITY_NODE;
115 
116     /**
117      * The node is a processing instruction.
118      *
119      * @see org.w3c.dom.Node#PROCESSING_INSTRUCTION_NODE
120      */
121     @JsxConstant
122     public static final int PROCESSING_INSTRUCTION_NODE = org.w3c.dom.Node.PROCESSING_INSTRUCTION_NODE;
123 
124     /**
125      * The node is a comment.
126      *
127      * @see org.w3c.dom.Node#COMMENT_NODE
128      */
129     @JsxConstant
130     public static final int COMMENT_NODE = org.w3c.dom.Node.COMMENT_NODE;
131 
132     /**
133      * The node is a document.
134      *
135      * @see org.w3c.dom.Node#DOCUMENT_NODE
136      */
137     @JsxConstant
138     public static final int DOCUMENT_NODE = org.w3c.dom.Node.DOCUMENT_NODE;
139 
140     /**
141      * The node is a document type.
142      *
143      * @see org.w3c.dom.Node#DOCUMENT_TYPE_NODE
144      */
145     @JsxConstant
146     public static final int DOCUMENT_TYPE_NODE = org.w3c.dom.Node.DOCUMENT_TYPE_NODE;
147 
148     /**
149      * The node is a document fragment.
150      *
151      * @see org.w3c.dom.Node#DOCUMENT_FRAGMENT_NODE
152      */
153     @JsxConstant
154     public static final int DOCUMENT_FRAGMENT_NODE = org.w3c.dom.Node.DOCUMENT_FRAGMENT_NODE;
155 
156     /**
157      * The node is a notation.
158      *
159      * @see org.w3c.dom.Node#NOTATION_NODE
160      */
161     @JsxConstant
162     public static final int NOTATION_NODE = org.w3c.dom.Node.NOTATION_NODE;
163 
164     /**
165      * The nodes are disconnected.
166      *
167      * @see org.w3c.dom.Node#DOCUMENT_POSITION_DISCONNECTED
168      */
169     @JsxConstant
170     public static final int DOCUMENT_POSITION_DISCONNECTED = org.w3c.dom.Node.DOCUMENT_POSITION_DISCONNECTED;
171 
172     /**
173      * The reference node precedes the other node.
174      *
175      * @see org.w3c.dom.Node#DOCUMENT_POSITION_PRECEDING
176      */
177     @JsxConstant
178     public static final int DOCUMENT_POSITION_PRECEDING = org.w3c.dom.Node.DOCUMENT_POSITION_PRECEDING;
179 
180     /**
181      * The reference node follows the other node.
182      *
183      * @see org.w3c.dom.Node#DOCUMENT_POSITION_FOLLOWING
184      */
185     @JsxConstant
186     public static final int DOCUMENT_POSITION_FOLLOWING = org.w3c.dom.Node.DOCUMENT_POSITION_FOLLOWING;
187 
188     /**
189      * The reference node contains the other node.
190      *
191      * @see org.w3c.dom.Node#DOCUMENT_POSITION_CONTAINS
192      */
193     @JsxConstant
194     public static final int DOCUMENT_POSITION_CONTAINS = org.w3c.dom.Node.DOCUMENT_POSITION_CONTAINS;
195 
196     /**
197      * The reference node is contained by the other node.
198      *
199      * @see org.w3c.dom.Node#DOCUMENT_POSITION_CONTAINED_BY
200      */
201     @JsxConstant
202     public static final int DOCUMENT_POSITION_CONTAINED_BY = org.w3c.dom.Node.DOCUMENT_POSITION_CONTAINED_BY;
203 
204     /**
205      * The document position is implementation-specific.
206      *
207      * @see org.w3c.dom.Node#DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
208      */
209     @JsxConstant
210     public static final int DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC
211         = org.w3c.dom.Node.DOCUMENT_POSITION_IMPLEMENTATION_SPECIFIC;
212 
213     /** "Live" child nodes collection; has to be a member to have equality (==) working. */
214     private NodeList childNodes_;
215 
216     /**
217      * JavaScript constructor.
218      */
219     @Override
220     @JsxConstructor
221     public void jsConstructor() {
222         super.jsConstructor();
223     }
224 
225     /**
226      * Gets the JavaScript property {@code nodeType} for the current node.
227      * @return the node type
228      */
229     @JsxGetter
230     public int getNodeType() {
231         return getDomNodeOrDie().getNodeType();
232     }
233 
234     /**
235      * Gets the JavaScript property {@code nodeName} for the current node.
236      * @return the node name
237      */
238     @JsxGetter
239     public String getNodeName() {
240         return getDomNodeOrDie().getNodeName();
241     }
242 
243     /**
244      * Gets the JavaScript property {@code nodeValue} for the current node.
245      * @return the node value
246      */
247     @JsxGetter
248     public String getNodeValue() {
249         return getDomNodeOrDie().getNodeValue();
250     }
251 
252     /**
253      * Sets the JavaScript property {@code nodeValue} for the current node.
254      * @param newValue the new node value
255      */
256     @JsxSetter
257     public void setNodeValue(final String newValue) {
258         getDomNodeOrDie().setNodeValue(newValue);
259     }
260 
261     /**
262      * Adds a DOM node to the node.
263      * @param childObject the node to add to this node
264      * @return the newly added child node
265      */
266     @JsxFunction
267     public Node appendChild(final Object childObject) {
268         final Node childNode = toNode(childObject, "appendChild", 1);
269 
270         // is the node allowed here?
271         if (!isNodeInsertable(childNode)) {
272             throw JavaScriptEngine.asJavaScriptException(
273                     getWindow(),
274                     "Node cannot be inserted at the specified point in the hierarchy",
275                     DOMException.HIERARCHY_REQUEST_ERR);
276         }
277 
278         // Get XML node for the DOM node passed in
279         final DomNode childDomNode = childNode.getDomNodeOrDie();
280 
281         // Get the parent XML node that the child should be added to.
282         final DomNode parentNode = getDomNodeOrDie();
283 
284         // Append the child to the parent node
285         try {
286             parentNode.appendChild(childDomNode);
287         }
288         catch (final org.w3c.dom.DOMException e) {
289             throw JavaScriptEngine.asJavaScriptException(getWindow(), e.getMessage(), e.code);
290         }
291 
292         initInlineFrameIfNeeded(childDomNode);
293         for (final HtmlElement htmlElement : childDomNode.getHtmlElementDescendants()) {
294             initInlineFrameIfNeeded(htmlElement);
295         }
296         return childNode;
297     }
298 
299     /**
300      * Checks that the given argument of a DOM function is a node; like in the browsers,
301      * a {@code TypeError} is thrown otherwise.
302      *
303      * @param arg the argument
304      * @param functionName the name of the function (for the error message)
305      * @param index the (1-based) index of the argument (for the error message)
306      * @return the node
307      */
308     private static Node toNode(final Object arg, final String functionName, final int index) {
309         if (arg instanceof Node node) {
310             return node;
311         }
312         throw JavaScriptEngine.typeError("Failed to execute '" + functionName + "' on 'Node': parameter "
313                 + index + " is not of type 'Node'.");
314     }
315 
316     /**
317      * If we have added a new iframe that
318      * had no source attribute, we have to take care the
319      * 'onload' handler is triggered.
320      */
321     private static void initInlineFrameIfNeeded(final DomNode childDomNode) {
322         if (childDomNode instanceof HtmlInlineFrame frame) {
323             if (DomElement.ATTRIBUTE_NOT_DEFINED == frame.getSrcAttribute()) {
324                 frame.loadInnerPage();
325             }
326         }
327     }
328 
329     /**
330      * Add a DOM node as a child to this node before the referenced node.
331      * If the referenced node is null, append to the end.
332      * @param context the JavaScript context
333      * @param scope the scope
334      * @param thisObj the scriptable
335      * @param args the arguments passed into the method
336      * @param function the function
337      * @return the newly added child node
338      */
339     @JsxFunction
340     public static Node insertBefore(final Context context, final VarScope scope,
341             final Scriptable thisObj, final Object[] args, final Function function) {
342         return ((Node) thisObj).insertBeforeImpl(args);
343     }
344 
345     /**
346      * Add a DOM node as a child to this node before the referenced node.
347      * If the referenced node is null, append to the end.
348      * @param args the arguments
349      * @return the newly added child node
350      */
351     protected Node insertBeforeImpl(final Object[] args) {
352         if (args.length < 1) {
353             throw JavaScriptEngine.typeError(
354                     "Failed to execute 'insertBefore' on 'Node': 2 arguments required, but only 0 present.");
355         }
356 
357         final Object newChildObject = args[0];
358         final Object refChildObject;
359         if (args.length > 1) {
360             refChildObject = args[1];
361         }
362         else {
363             refChildObject = JavaScriptEngine.UNDEFINED;
364         }
365 
366         final Node newChild = toNode(newChildObject, "insertBefore", 1);
367 
368         // is the node allowed here?
369         if (!isNodeInsertable(newChild)) {
370             throw JavaScriptEngine.asJavaScriptException(
371                     getWindow(),
372                     "Node cannot be inserted at the specified point in the hierarchy",
373                     DOMException.HIERARCHY_REQUEST_ERR);
374         }
375 
376         final DomNode newChildNode = newChild.getDomNodeOrDie();
377         if (newChildNode instanceof DomDocumentFragment fragment) {
378             for (final DomNode child : fragment.getChildren()) {
379                 if (!isNodeInsertable(child.getScriptableObject())) {
380                     throw JavaScriptEngine.asJavaScriptException(
381                             getWindow(),
382                             "Node cannot be inserted at the specified point in the hierarchy",
383                             DOMException.HIERARCHY_REQUEST_ERR);
384                 }
385             }
386         }
387 
388         // extract refChild
389         final DomNode refChildNode;
390         if (JavaScriptEngine.isUndefined(refChildObject)) {
391             if (args.length == 2) {
392                 refChildNode = null;
393             }
394             else {
395                 throw JavaScriptEngine.typeError(
396                         "Failed to execute 'insertBefore' on 'Node': 2 arguments required, but only 1 present.");
397             }
398         }
399         else if (refChildObject == null) {
400             refChildNode = null;
401         }
402         else {
403             refChildNode = toNode(refChildObject, "insertBefore", 2).getDomNodeOrDie();
404         }
405 
406         final DomNode domNode = getDomNodeOrDie();
407 
408         try {
409             domNode.insertBefore(newChildNode, refChildNode);
410         }
411         catch (final org.w3c.dom.DOMException e) {
412             throw JavaScriptEngine.asJavaScriptException(getWindow(), e.getMessage(), DOMException.NOT_FOUND_ERR);
413         }
414         return newChild;
415     }
416 
417     /**
418      * Indicates if the node can be inserted.
419      * @param childObject the node
420      * @return {@code false} if it is not allowed here
421      */
422     private static boolean isNodeInsertable(final Node childObject) {
423         if (childObject instanceof HTMLHtmlElement) {
424             final DomNode domNode = childObject.getDomNodeOrDie();
425             return domNode.getPage().getDocumentElement() != domNode;
426         }
427         return true;
428     }
429 
430     /**
431      * Removes the DOM node from its parent.
432      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove">MDN documentation</a>
433      */
434     protected void remove() {
435         getDomNodeOrDie().remove();
436     }
437 
438     /**
439      * Removes a DOM node from this node.
440      * @param childObject the node to remove from this node
441      * @return the removed child node
442      */
443     @JsxFunction
444     public Node removeChild(final Object childObject) {
445         final Node childObjectNode = toNode(childObject, "removeChild", 1);
446 
447         // Get XML node for the DOM node passed in
448         final DomNode childDomNode = childObjectNode.getDomNodeOrDie();
449 
450         if (!getDomNodeOrDie().isAncestorOf(childDomNode)) {
451             throw JavaScriptEngine.asJavaScriptException(
452                     getWindow(),
453                     "Failed to execute 'removeChild' on '"
454                             + this + "': The node to be removed is not a child of this node.",
455                     DOMException.NOT_FOUND_ERR);
456         }
457         // Remove the child from the parent node
458         childDomNode.remove();
459         return childObjectNode;
460     }
461 
462     /**
463      * Replaces a child DOM node with another DOM node.
464      * @param newChildObject the node to add as a child of this node
465      * @param oldChildObject the node to remove as a child of this node
466      * @return the removed child node
467      */
468     @JsxFunction
469     public Node replaceChild(final Object newChildObject, final Object oldChildObject) {
470         toNode(newChildObject, "replaceChild", 1);
471         final Node oldChild = toNode(oldChildObject, "replaceChild", 2);
472         if (oldChild.getDomNodeOrDie().getParentNode() != getDomNodeOrDie()) {
473             throw JavaScriptEngine.asJavaScriptException(
474                     getWindow(),
475                     "Failed to execute 'replaceChild' on 'Node': The node to be replaced is not a child of this node.",
476                     DOMException.NOT_FOUND_ERR);
477         }
478 
479         if (newChildObject instanceof DocumentFragment fragment) {
480             Node firstNode = null;
481 
482             final Node oldChildNode = (Node) oldChildObject;
483             final Node refChildObject = oldChildNode.getNextSibling();
484             for (final DomNode node : fragment.getDomNodeOrDie().getChildren()) {
485                 if (firstNode == null) {
486                     replaceChild(node.getScriptableObject(), oldChildObject);
487                     firstNode = node.getScriptableObject();
488                 }
489                 else {
490                     insertBeforeImpl(new Object[] {node.getScriptableObject(), refChildObject});
491                 }
492             }
493             if (firstNode == null) {
494                 removeChild(oldChildObject);
495             }
496 
497             return oldChildNode;
498         }
499 
500         if (newChildObject instanceof Node newChild && oldChildObject instanceof Node oldChildNode) {
501 
502             // is the node allowed here?
503             if (!isNodeInsertable(newChild)) {
504                 throw JavaScriptEngine.asJavaScriptException(
505                         getWindow(),
506                         "Node cannot be inserted at the specified point in the hierarchy",
507                         DOMException.HIERARCHY_REQUEST_ERR);
508             }
509 
510             // Get XML nodes for the DOM nodes passed in
511             final DomNode newChildDomNode = newChild.getDomNodeOrDie();
512             final DomNode oldChildDomNode = oldChildNode.getDomNodeOrDie();
513 
514             // Replace the old child with the new child.
515             oldChildDomNode.replace(newChildDomNode);
516 
517             return oldChildNode;
518         }
519 
520         return null;
521     }
522 
523     /**
524      * Implementation of moveBefore() of the ParentNode mixin
525      * (available for Element, Document and DocumentFragment, but not for Node).
526      * Moves a given node inside the invoking node as a direct child, before a given reference node.
527      *
528      * @param thisObj the parent node
529      * @param args the arguments passed into the JavaScript function
530      * @param interfaceName the name of the interface used for the error messages (e.g. 'Element')
531      */
532     protected static void moveBeforeImpl(final Scriptable thisObj, final Object[] args,
533             final String interfaceName) {
534         if (args.length < 2) {
535             throw JavaScriptEngine.typeError(
536                     "Failed to execute 'moveBefore' on '" + interfaceName + "': 2 arguments required, but only "
537                     + args.length + " present.");
538         }
539 
540         if (!(args[0] instanceof Node movedNode)) {
541             throw JavaScriptEngine.typeError(
542                     "Failed to execute 'moveBefore' on '" + interfaceName + "': parameter 1 is not of type 'Node'.");
543         }
544 
545         // the reference node is nullable; undefined is converted to null
546         final Object referenceNodeObject = JavaScriptEngine.isUndefined(args[1]) ? null : args[1];
547         if (referenceNodeObject != null && !(referenceNodeObject instanceof Node)) {
548             throw JavaScriptEngine.typeError(
549                     "Failed to execute 'moveBefore' on '" + interfaceName + "': parameter 2 is not of type 'Node'.");
550         }
551 
552         final Node node = (Node) thisObj;
553         try {
554             node.getDomNodeOrDie().moveBefore(movedNode.getDomNodeOrDie(),
555                     referenceNodeObject == null ? null : ((Node) referenceNodeObject).getDomNodeOrDie());
556         }
557         catch (final org.w3c.dom.DOMException e) {
558             throw JavaScriptEngine.asJavaScriptException(
559                     node.getWindow(),
560                     "Failed to execute 'moveBefore' on '" + interfaceName + "': " + e.getMessage(),
561                     e.code);
562         }
563     }
564 
565     /**
566      * Clones this node.
567      * @param deep if {@code true}, recursively clones all descendants
568      * @return the newly cloned node
569      */
570     @JsxFunction
571     public Node cloneNode(final boolean deep) {
572         final DomNode domNode = getDomNodeOrDie();
573         final DomNode clonedNode = domNode.cloneNode(deep);
574 
575         return getJavaScriptNode(clonedNode);
576     }
577 
578     /**
579      * Determines whether this node is structurally equal to the specified node.
580      *
581      * @param other the node to compare with
582      * @return {@code true} if the two nodes are structurally equal
583      * @see <a href="https://dom.spec.whatwg.org/#concept-node-equals">WHATWG DOM: concept-node-equals</a>
584      */
585     @JsxFunction
586     public boolean isEqualNode(final Node other) {
587         if (isSameNode(other)) {
588             return true;
589         }
590 
591         if (other == null) {
592             return false;
593         }
594 
595         if (!getClassName().equals(other.getClassName())) {
596             return false;
597         }
598 
599         if (this instanceof DocumentType docType) {
600             final DocumentType otherDocType = (DocumentType) other;
601             if (!Objects.equals(docType.getName(), otherDocType.getName())
602                     || !Objects.equals(docType.getPublicId(), otherDocType.getPublicId())
603                     || !Objects.equals(docType.getSystemId(), otherDocType.getSystemId())) {
604                 return false;
605             }
606 
607         }
608         else if (this instanceof Element element) {
609             final Element otherElement = (Element) other;
610             if (!Objects.equals(element.getNodeName(), otherElement.getNodeName())
611                     || !Objects.equals(element.getPrefix(), otherElement.getPrefix())
612                     || !Objects.equals(element.getLocalName(), otherElement.getLocalName())) {
613                 return false;
614             }
615 
616             final NamedNodeMap attributesMap = element.getAttributes();
617             final NamedNodeMap otherAttributesMap = otherElement.getAttributes();
618             if (attributesMap != null || otherAttributesMap != null) {
619                 if (attributesMap == null || otherAttributesMap == null) {
620                     return false;
621                 }
622 
623                 final int length = attributesMap.getLength();
624                 if (length != otherAttributesMap.getLength()) {
625                     return false;
626                 }
627 
628                 final Map<String, Attr> name2Attributes = new HashMap<>();
629                 for (int i = 0; i < length; i++) {
630                     final Attr attribute = (Attr) attributesMap.item(i);
631                     name2Attributes.put(attribute.getName(), attribute);
632                 }
633 
634                 for (int i = 0; i < length; i++) {
635                     final Attr otherAttribute = (Attr) otherAttributesMap.item(i);
636                     final Attr attribute = name2Attributes.get(otherAttribute.getName());
637                     if (attribute == null) {
638                         return false;
639                     }
640                     if (!attribute.isEqualNode(otherAttribute)) {
641                         return false;
642                     }
643                 }
644             }
645 
646         }
647         else if (this instanceof Attr attr) {
648             final Attr otherAttr = (Attr) other;
649             if (!Objects.equals(attr.getName(), otherAttr.getName())
650                     || !Objects.equals(attr.getLocalName(), otherAttr.getLocalName())
651                     || !Objects.equals(attr.getValue(), otherAttr.getValue())) {
652                 return false;
653             }
654 
655         }
656         else if (this instanceof ProcessingInstruction instruction) {
657             final ProcessingInstruction otherInstruction = (ProcessingInstruction) other;
658             if (!Objects.equals(instruction.getTarget(), otherInstruction.getTarget())
659                     || !Objects.equals(instruction.getData(), otherInstruction.getData())) {
660                 return false;
661             }
662 
663         }
664         else if (this instanceof Text || this instanceof Comment) {
665             final CharacterData data = (CharacterData) this;
666             final CharacterData otherData = (CharacterData) other;
667             if (!Objects.equals(data.getData(), otherData.getData())) {
668                 return false;
669             }
670         }
671 
672         final NodeList childNodes = getChildNodes();
673         final NodeList otherChildNodes = other.getChildNodes();
674         if (childNodes != null || otherChildNodes != null) {
675             if (childNodes == null || otherChildNodes == null) {
676                 return false;
677             }
678 
679             final int length = childNodes.getLength();
680             final int otherLength = otherChildNodes.getLength();
681             if (length != otherLength) {
682                 return false;
683             }
684 
685             for (int i = 0; i < length; i++) {
686                 final Node childNode = (Node) childNodes.item(i);
687                 final Node otherChildNode = (Node) otherChildNodes.item(i);
688                 if (!childNode.isEqualNode(otherChildNode)) {
689                     return false;
690                 }
691             }
692         }
693 
694         return true;
695     }
696 
697     /**
698      * Determines whether this node and the specified node are the same object.
699      *
700      * @param other the node to test against
701      * @return {@code true} if this node is the same node as the given one
702      */
703     @JsxFunction
704     public boolean isSameNode(final Object other) {
705         return this == other;
706     }
707 
708     /**
709      * Returns whether this node has any child nodes.
710      *
711      * @return {@code true} if this node has any child nodes
712      */
713     @JsxFunction
714     public boolean hasChildNodes() {
715         return getDomNodeOrDie().getChildren().iterator().hasNext();
716     }
717 
718     /**
719      * Returns the namespace prefix for the specified namespace URI.
720      *
721      * @param namespace the namespace URI
722      * @return the corresponding namespace prefix, or {@code null} if none exists;
723      *         if multiple prefixes are possible, the first one is returned
724      */
725     @JsxFunction
726     public String lookupPrefix(final String namespace) {
727         return null;
728     }
729 
730     /**
731      * Returns the child nodes of the current element.
732      * @return the child nodes of the current element
733      */
734     @JsxGetter
735     public NodeList getChildNodes() {
736         if (childNodes_ == null) {
737             final DomNode node = getDomNodeOrDie();
738             childNodes_ = new NodeList(node, false);
739             childNodes_.setElementsSupplier(
740                     (Supplier<List<DomNode>> & Serializable)
741                     () -> {
742                         final List<DomNode> response = new ArrayList<>();
743                         for (final DomNode child : node.getChildren()) {
744                             response.add(child);
745                         }
746 
747                         return response;
748                     });
749         }
750         return childNodes_;
751     }
752 
753     /**
754      * Returns this node's parent node.
755      * @return this node's parent node
756      */
757     public final Node getParent() {
758         return getJavaScriptNode(getDomNodeOrDie().getParentNode());
759     }
760 
761     /**
762      * Gets the JavaScript property {@code parentNode} for the node that
763      * contains the current node.
764      * @return the parent node
765      */
766     @JsxGetter
767     public Object getParentNode() {
768         return getJavaScriptNode(getDomNodeOrDie().getParentNode());
769     }
770 
771     /**
772      * Gets the JavaScript property {@code nextSibling} for the node that
773      * contains the current node.
774      * @return the next sibling node or null if the current node has
775      *         no next sibling.
776      */
777     @JsxGetter
778     public Node getNextSibling() {
779         return getJavaScriptNode(getDomNodeOrDie().getNextSibling());
780     }
781 
782     /**
783      * Gets the JavaScript property {@code previousSibling} for the node that
784      * contains the current node.
785      * @return the previous sibling node or null if the current node has
786      *         no previous sibling.
787      */
788     @JsxGetter
789     public Node getPreviousSibling() {
790         return getJavaScriptNode(getDomNodeOrDie().getPreviousSibling());
791     }
792 
793     /**
794      * Gets the JavaScript property {@code firstChild} for the node that
795      * contains the current node.
796      * @return the first child node or null if the current node has
797      *         no children.
798      */
799     @JsxGetter
800     public Node getFirstChild() {
801         return getJavaScriptNode(getDomNodeOrDie().getFirstChild());
802     }
803 
804     /**
805      * Gets the JavaScript property {@code lastChild} for the node that
806      * contains the current node.
807      * @return the last child node or null if the current node has
808      *         no children.
809      */
810     @JsxGetter
811     public Node getLastChild() {
812         return getJavaScriptNode(getDomNodeOrDie().getLastChild());
813     }
814 
815     /**
816      * Gets the JavaScript node for a given DomNode.
817      * @param domNode the DomNode
818      * @return the JavaScript node or null if the DomNode was null
819      */
820     protected Node getJavaScriptNode(final DomNode domNode) {
821         if (domNode == null) {
822             return null;
823         }
824         return (Node) getScriptableFor(domNode);
825     }
826 
827     /**
828      * Returns the owner document.
829      * @return the document
830      */
831     @JsxGetter
832     public HtmlUnitScriptable getOwnerDocument() {
833         final Object document = getDomNodeOrDie().getOwnerDocument();
834         if (document != null) {
835             return ((SgmlPage) document).getScriptableObject();
836         }
837         return null;
838     }
839 
840     /**
841      * Returns the root node of this node's tree.
842      *
843      * @return the root node
844      */
845     @JsxFunction
846     public Node getRootNode() {
847         Node parent = this;
848         while (parent != null) {
849             if (parent instanceof Document || parent instanceof DocumentFragment) {
850                 return parent;
851             }
852             parent = parent.getParent();
853         }
854         return this;
855     }
856 
857     /**
858      * Compares the positions of this node and the provided node within the document.
859      * @param nodeObject node object that specifies the node to check
860      * @return how the node is positioned relatively to the reference node.
861      * @see <a href="http://www.w3.org/TR/DOM-Level-3-Core/core.html#Node3-compareDocumentPosition">DOM level 3</a>
862      * @see org.w3c.dom.Node#compareDocumentPosition(org.w3c.dom.Node)
863      */
864     @JsxFunction
865     public int compareDocumentPosition(final Object nodeObject) {
866         if (!(nodeObject instanceof Node node)) {
867             throw JavaScriptEngine.typeError("Could not convert JavaScript argument arg 0");
868         }
869         return getDomNodeOrDie().compareDocumentPosition(node.getDomNodeOrDie());
870     }
871 
872     /**
873      * Merges adjacent TextNode objects to produce a normalized document object model.
874      */
875     @JsxFunction
876     public void normalize() {
877         getDomNodeOrDie().normalize();
878     }
879 
880     /**
881      * Gets the textContent attribute.
882      * @return the contents of this node as text
883      */
884     @JsxGetter
885     public String getTextContent() {
886         return getDomNodeOrDie().getTextContent();
887     }
888 
889     /**
890      * Replace all children elements of this element with the supplied value.
891      * @param value - the new value for the contents of this node
892      */
893     @JsxSetter
894     public void setTextContent(final Object value) {
895         getDomNodeOrDie().setTextContent(value == null ? null : JavaScriptEngine.toString(value));
896     }
897 
898     /**
899      * Gets the JavaScript property {@code parentElement}.
900      * @return the parent element
901      * @see #getParentNode()
902      */
903     @JsxGetter
904     public Element getParentElement() {
905         final Node parent = getParent();
906         if (!(parent instanceof Element)) {
907             return null;
908         }
909         return (Element) parent;
910     }
911 
912     /**
913      * Returns the attributes of this XML element.
914      * @see <a href="https://developer.mozilla.org/en-US/docs/DOM/Node.attributes">Gecko DOM Reference</a>
915      * @return the attributes of this XML element
916      */
917     public NamedNodeMap getAttributes() {
918         return null;
919     }
920 
921     /**
922      * Returns whether the specified node is contained within this node.
923      *
924      * @param element the node to check
925      * @return {@code true} if the specified node is contained within this node
926      */
927     @JsxFunction
928     public boolean contains(final Object element) {
929         if (element == null || JavaScriptEngine.isUndefined(element)) {
930             return false;
931         }
932 
933         if (!(element instanceof Node parent)) {
934             throw JavaScriptEngine.reportRuntimeError("Could not convert JavaScript argument arg 0");
935         }
936 
937         for ( ; parent != null; parent = parent.getParentElement()) {
938             if (this == parent) {
939                 return true;
940             }
941         }
942         return false;
943     }
944 
945     /**
946      * Returns the Base URI as a string.
947      * @return the Base URI as a string
948      */
949     @JsxGetter
950     public String getBaseURI() {
951         return getDomNodeOrDie().getBaseURI();
952     }
953 
954     /**
955      * Returns whether this node has any attributes.
956      *
957      * @return {@code true} if this node has one or more attributes
958      */
959     public boolean hasAttributes() {
960         return getDomNodeOrDie().hasAttributes();
961     }
962 
963     /**
964      * Returns the namespace prefix.
965      * @return the namespace prefix
966      */
967     public String getPrefix() {
968         return getDomNodeOrDie().getPrefix();
969     }
970 
971     /**
972      * Returns the local name of this attribute.
973      * @return the local name of this attribute
974      */
975     public String getLocalName() {
976         return getDomNodeOrDie().getLocalName();
977     }
978 
979     /**
980      * Returns the URI that identifies an XML namespace.
981      * @return the URI that identifies an XML namespace
982      */
983     public String getNamespaceURI() {
984         return getDomNodeOrDie().getNamespaceURI();
985     }
986 
987     /**
988      * Returns the current number of child elements.
989      * @return the child element count
990      */
991     protected int getChildElementCount() {
992         final DomNode domNode = getDomNodeOrDie();
993         if (domNode instanceof DomElement element) {
994             return element.getChildElementCount();
995         }
996 
997         int counter = 0;
998         for (final DomNode child : getDomNodeOrDie().getChildren()) {
999             if (child != null) {
1000                 final HtmlUnitScriptable scriptable = child.getScriptableObject();
1001                 if (scriptable instanceof Element) {
1002                     counter++;
1003                 }
1004             }
1005         }
1006         return counter;
1007     }
1008 
1009     /**
1010      * Returns the first element child.
1011      * @return the first element child
1012      */
1013     protected Element getFirstElementChild() {
1014         final DomNode domNode = getDomNodeOrDie();
1015         if (domNode instanceof DomElement element) {
1016             final DomElement child = element.getFirstElementChild();
1017             if (child != null) {
1018                 return child.getScriptableObject();
1019             }
1020             return null;
1021         }
1022 
1023         for (final DomNode child : domNode.getChildren()) {
1024             if (child != null) {
1025                 final HtmlUnitScriptable scriptable = child.getScriptableObject();
1026                 if (scriptable instanceof Element element) {
1027                     return element;
1028                 }
1029             }
1030         }
1031         return null;
1032     }
1033 
1034     /**
1035      * Returns the last element child.
1036      * @return the last element child
1037      */
1038     protected Element getLastElementChild() {
1039         final DomNode domNode = getDomNodeOrDie();
1040         if (domNode instanceof DomElement) {
1041             final DomElement child = ((DomElement) getDomNodeOrDie()).getLastElementChild();
1042             if (child != null) {
1043                 return child.getScriptableObject();
1044             }
1045             return null;
1046         }
1047 
1048         Element result = null;
1049         for (final DomNode child : domNode.getChildren()) {
1050             final HtmlUnitScriptable scriptable = child.getScriptableObject();
1051             if (scriptable instanceof Element element) {
1052                 result = element;
1053             }
1054         }
1055         return result;
1056     }
1057 
1058     /**
1059      * Returns the child elements of this node.
1060      *
1061      * @return a live collection of this node's child elements
1062      * @see <a href="https://developer.mozilla.org/en-US/docs/Web/API/ParentNode/children">MDN documentation</a>
1063      */
1064     protected HTMLCollection getChildren() {
1065         final DomNode node = getDomNodeOrDie();
1066         final HTMLCollection childrenColl = new HTMLCollection(node, false);
1067         childrenColl.setElementsSupplier(
1068                 (Supplier<List<DomNode>> & Serializable)
1069                 () -> {
1070                     final List<DomNode> children = new ArrayList<>();
1071                     for (final DomNode domNode : node.getChildNodes()) {
1072                         if (domNode instanceof DomElement) {
1073                             children.add(domNode);
1074                         }
1075                     }
1076                     return children;
1077                 });
1078         return childrenColl;
1079     }
1080 
1081     /**
1082      * Inserts a set of Node or DOMString objects in the children list of this ChildNode's parent,
1083      * just after this ChildNode.
1084      * @param context the context
1085      * @param thisObj this object
1086      * @param args the arguments
1087      * @param function the function
1088      */
1089     protected static void after(final Context context, final Scriptable thisObj, final Object[] args,
1090             final Function function) {
1091         final DomNode thisDomNode = ((Node) thisObj).getDomNodeOrDie();
1092         final DomNode parentNode = thisDomNode.getParentNode();
1093         final DomNode nextSibling = thisDomNode.getNextSibling();
1094         for (final Object arg : args) {
1095             final Node node = toNodeOrTextNode((Node) thisObj, arg);
1096             final DomNode newNode = node.getDomNodeOrDie();
1097             if (nextSibling == null) {
1098                 parentNode.appendChild(newNode);
1099             }
1100             else {
1101                 nextSibling.insertBefore(newNode);
1102             }
1103         }
1104     }
1105 
1106     /**
1107      * Inserts a set of Node objects or string objects after the last child of the Element.
1108      * String objects are inserted as equivalent Text nodes.
1109      * @param context the context
1110      * @param thisObj this object
1111      * @param args the arguments
1112      * @param function the function
1113      */
1114     protected static void append(final Context context, final Scriptable thisObj, final Object[] args,
1115             final Function function) {
1116         if (!(thisObj instanceof Node thisNode)) {
1117             throw JavaScriptEngine.typeError("Illegal invocation");
1118         }
1119 
1120         final DomNode thisDomNode = thisNode.getDomNodeOrDie();
1121 
1122         for (final Object arg : args) {
1123             final Node node = toNodeOrTextNode(thisNode, arg);
1124             thisDomNode.appendChild(node.getDomNodeOrDie());
1125         }
1126     }
1127 
1128     /**
1129      * Inserts a set of Node objects or string objects before the first child of the Element.
1130      * String objects are inserted as equivalent Text nodes.
1131      * @param context the context
1132      * @param thisObj this object
1133      * @param args the arguments
1134      * @param function the function
1135      */
1136     protected static void prepend(final Context context, final Scriptable thisObj, final Object[] args,
1137             final Function function) {
1138         if (!(thisObj instanceof Node thisNode)) {
1139             throw JavaScriptEngine.typeError("Illegal invocation");
1140         }
1141 
1142         final DomNode thisDomNode = thisNode.getDomNodeOrDie();
1143         final DomNode firstChild = thisDomNode.getFirstChild();
1144 
1145         for (final Object arg : args) {
1146             final Node node = toNodeOrTextNode(thisNode, arg);
1147             final DomNode newNode = node.getDomNodeOrDie();
1148             if (firstChild == null) {
1149                 thisDomNode.appendChild(newNode);
1150             }
1151             else {
1152                 firstChild.insertBefore(newNode);
1153             }
1154         }
1155     }
1156 
1157     /**
1158      * Replaces the existing children of a Node with a specified new set of children.
1159      * These can be string or Node objects.
1160      * @param context the context
1161      * @param thisObj this object
1162      * @param args the arguments
1163      * @param function the function
1164      */
1165     protected static void replaceChildren(final Context context, final Scriptable thisObj, final Object[] args,
1166             final Function function) {
1167         if (!(thisObj instanceof Node thisNode)) {
1168             throw JavaScriptEngine.typeError("Illegal invocation");
1169         }
1170 
1171         final DomNode thisDomNode = thisNode.getDomNodeOrDie();
1172         thisDomNode.removeAllChildren();
1173 
1174         for (final Object arg : args) {
1175             final Node node = toNodeOrTextNode(thisNode, arg);
1176             thisDomNode.appendChild(node.getDomNodeOrDie());
1177         }
1178     }
1179 
1180     private static Node toNodeOrTextNode(final Node thisObj, final Object obj) {
1181         if (obj instanceof Node node) {
1182             return node;
1183         }
1184         return (Node)
1185                 ((HTMLDocument) thisObj.getOwnerDocument()).createTextNode(JavaScriptEngine.toString(obj));
1186     }
1187 
1188     /**
1189      * Inserts a set of Node or DOMString objects in the children list of this ChildNode's parent,
1190      * just before this ChildNode.
1191      * @param context the context
1192      * @param thisObj this object
1193      * @param args the arguments
1194      * @param function the function
1195      */
1196     protected static void before(final Context context, final Scriptable thisObj, final Object[] args,
1197             final Function function) {
1198         for (final Object arg : args) {
1199             final Node node = toNodeOrTextNode((Node) thisObj, arg);
1200             ((Node) thisObj).getDomNodeOrDie().insertBefore(node.getDomNodeOrDie());
1201         }
1202     }
1203 
1204     /**
1205      * Replaces this ChildNode in the children list of its parent with a set of Node or DOMString objects.
1206      * @param context the context
1207      * @param thisObj this object
1208      * @param args the arguments
1209      * @param function the function
1210      */
1211     protected static void replaceWith(final Context context, final Scriptable thisObj, final Object[] args,
1212             final Function function) {
1213         final DomNode thisDomNode = ((Node) thisObj).getDomNodeOrDie();
1214         final DomNode parentNode = thisDomNode.getParentNode();
1215 
1216         if (args.length == 0) {
1217             parentNode.removeChild(thisDomNode);
1218             return;
1219         }
1220 
1221         final DomNode nextSibling = thisDomNode.getNextSibling();
1222         boolean isFirst = true;
1223         for (final Object arg : args) {
1224             final DomNode newNode = toNodeOrTextNode((Node) thisObj, arg).getDomNodeOrDie();
1225             if (isFirst) {
1226                 isFirst = false;
1227                 thisDomNode.replace(newNode);
1228             }
1229             else {
1230                 if (nextSibling == null) {
1231                     parentNode.appendChild(newNode);
1232                 }
1233                 else {
1234                     nextSibling.insertBefore(newNode);
1235                 }
1236             }
1237         }
1238     }
1239 }