Skip to content

Commit fac414d

Browse files
committed
Create method insert_before() (#16)
1 parent 122b77e commit fac414d

File tree

1 file changed

+42
-0
lines changed
  • w3/python/core/fundamental_interface

1 file changed

+42
-0
lines changed

w3/python/core/fundamental_interface/Node.py

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -266,6 +266,48 @@ def _set_owner_document(self,
266266
"""Indirect accessor to set the 'owner_document' property."""
267267
self._owner_document = owner_document
268268

269+
def insert_before(self,
270+
new_child: _AnyNode,
271+
ref_child: Optional[_AnyNode] = None) -> _AnyNode:
272+
"""Inserts the node `new_child` before the existing child node `ref_child`. If `ref_child` is `None`, insert `new_child` at the end of the list of children.
273+
274+
If `new_child` is a `DocumentFragment` object, all of its children are inserted, in the same order, before `ref_child`. If the `new_child` is already in the tree, it is first removed.
275+
276+
Args:
277+
new_child: The node to insert.
278+
ref_child: The reference node, i.e., the node before which the new node must be inserted.
279+
280+
Returns:
281+
The node being inserted.
282+
283+
Raises:
284+
DOMException:
285+
- `HIERARCHY_REQUEST_ERR`: Raised if this node is of a type that does not allow children of the type of the `new_child` node, or if the node to insert is one of this node's ancestors.
286+
- `WRONG_DOCUMENT_ERR`: Raised if `new_child` was created from a different document than the one that created this node.
287+
- `NO_MODIFICATION_ALLOWED_ERR`: Raised if this node is readonly.
288+
- `NOT_FOUND_ERR`: Raised if `ref_child` is not a child of this node.
289+
"""
290+
if self._read_only:
291+
raise DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)
292+
if self.owner_document is not new_child.owner_document:
293+
raise DOMException(DOMException.WRONG_DOCUMENT_ERR)
294+
# `HIERARCHY_REQUEST_ERR` should be checked on subclasses by overriding.
295+
if new_child in self.child_nodes:
296+
self.child_nodes.remove(new_child)
297+
if new_child.node_type == NodeType.DOCUMENT_FRAGMENT_NODE:
298+
grand_child_node: _AnyNode
299+
for grand_child_node in new_child.child_nodes:
300+
self.insert_before(grand_child_node, ref_child)
301+
elif ref_child is None:
302+
self.child_nodes.append(new_child)
303+
elif ref_child not in self.child_nodes:
304+
raise DOMException(DOMException.NOT_FOUND_ERR)
305+
else:
306+
self.child_nodes.insert(self.child_nodes.index(ref_child),
307+
new_child)
308+
new_child._set_parent_node(self)
309+
return new_child
310+
269311
def has_child_nodes(self) -> bool:
270312
"""This is a convenience method to allow easy determination of whether a node has any children.
271313

0 commit comments

Comments
 (0)