Skip to content

Commit 7c5ed53

Browse files
committed
#16 Add comment for Node.insert_before()
1 parent f51f5a9 commit 7c5ed53

File tree

1 file changed

+27
-11
lines changed
  • w3/python/core/fundamental_interface

1 file changed

+27
-11
lines changed

w3/python/core/fundamental_interface/Node.py

Lines changed: 27 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -280,24 +280,40 @@ def insert_before(self,
280280
- `NO_MODIFICATION_ALLOWED_ERR`: Raised if this node is readonly.
281281
- `NOT_FOUND_ERR`: Raised if `ref_child` is not a child of this node.
282282
"""
283+
# `HIERARCHY_REQUEST_ERR` should be checked on subclasses by overriding.
283284
if self._read_only:
284285
raise DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)
285-
if self.owner_document is not new_child.owner_document:
286+
if new_child.owner_document is not self.owner_document:
286287
raise DOMException(DOMException.WRONG_DOCUMENT_ERR)
287-
# `HIERARCHY_REQUEST_ERR` should be checked on subclasses by overriding.
288-
if new_child in self.child_nodes:
289-
self.child_nodes.remove(new_child)
288+
if ref_child is not None:
289+
if ref_child not in self.child_nodes:
290+
raise DOMException(DOMException.NOT_FOUND_ERR)
291+
# If `new_child` and `old_child` share the same reference,
292+
# this method does nothing.
293+
if new_child is ref_child:
294+
return new_child
295+
# If `ref_child` is null, insert `new_child` at the end of the list of children.
296+
#
297+
# This operation is equivalent to the `append_child()` method.
298+
if ref_child is None:
299+
self.append_child(new_child)
300+
return new_child
301+
# If `new_child` is a `DocumentFragment` object,
302+
# all of its children are inserted, in the same order.
303+
#
304+
# This is done by recursive calls.
290305
if new_child.node_type == NodeType.DOCUMENT_FRAGMENT_NODE:
291306
grand_child_node: _AnyNode
292307
for grand_child_node in new_child.child_nodes:
293308
self.insert_before(grand_child_node, ref_child)
294-
elif ref_child is None:
295-
self.child_nodes.append(new_child)
296-
elif ref_child not in self.child_nodes:
297-
raise DOMException(DOMException.NOT_FOUND_ERR)
298-
else:
299-
self.child_nodes.insert(self.child_nodes.index(ref_child),
300-
new_child)
309+
return new_child
310+
# If the `new_child` is already in the tree,
311+
# it is first removed.
312+
if new_child in self.child_nodes:
313+
self.child_nodes.remove(new_child)
314+
# Otherwise, simply insert `new_child` using the methods of `NodeList(list)`.
315+
ref_index = self.child_nodes.index(ref_child)
316+
self.child_nodes.insert(ref_index, new_child)
301317
new_child._set_parent_node(self)
302318
return new_child
303319

0 commit comments

Comments
 (0)