@@ -280,24 +280,40 @@ def insert_before(self,
280
280
- `NO_MODIFICATION_ALLOWED_ERR`: Raised if this node is readonly.
281
281
- `NOT_FOUND_ERR`: Raised if `ref_child` is not a child of this node.
282
282
"""
283
+ # `HIERARCHY_REQUEST_ERR` should be checked on subclasses by overriding.
283
284
if self ._read_only :
284
285
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 :
286
287
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.
290
305
if new_child .node_type == NodeType .DOCUMENT_FRAGMENT_NODE :
291
306
grand_child_node : _AnyNode
292
307
for grand_child_node in new_child .child_nodes :
293
308
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 )
301
317
new_child ._set_parent_node (self )
302
318
return new_child
303
319
0 commit comments