Skip to content

Commit f51f5a9

Browse files
committed
#16 Create method Node.replace_child()
1 parent ec6f7f9 commit f51f5a9

File tree

1 file changed

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

1 file changed

+41
-0
lines changed

w3/python/core/fundamental_interface/Node.py

Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -301,6 +301,47 @@ def insert_before(self,
301301
new_child._set_parent_node(self)
302302
return new_child
303303

304+
def replace_child(self,
305+
new_child: _AnyNode,
306+
old_child: _AnyNode) -> _AnyNode:
307+
"""Replaces the child node `old_child` with `new_child` in the list of children, and returns the `old_child` node.
308+
309+
If the `new_child` is already in the tree, it is first removed.
310+
311+
Args:
312+
new_child: The new node to put in the child list.
313+
old_child: The node being replaced in the list.
314+
315+
Returns:
316+
The node replaced.
317+
318+
Raisees:
319+
DOMException:
320+
- `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 it the node to put in is one of this node's ancestors.
321+
- `WRONG_DOCUMENT_ERR`: Raised if `new_child` was created from a different document than the one that created this node.
322+
- `NO_MODIFICATION_ALLOWED_ERR`: Raised if this node is readonly.
323+
- `NOT_FOUND_ERR`: Raised if `old_child` is not a child of this node.
324+
"""
325+
# `HIERARCHY_REQUEST_ERR` should be checked on subclasses by overriding.
326+
if self._read_only:
327+
raise DOMException(DOMException.NO_MODIFICATION_ALLOWED_ERR)
328+
if new_child.owner_document is not self.owner_document:
329+
raise DOMException(DOMException.WRONG_DOCUMENT_ERR)
330+
if old_child not in self.child_nodes:
331+
raise DOMException(DOMException.NOT_FOUND_ERR)
332+
# If `new_child` and `old_child` share the same reference,
333+
# this method does nothing.
334+
if new_child is old_child:
335+
return old_child
336+
# If the `new_child` is already in the tree,
337+
# it is first removed.
338+
if new_child in self.child_nodes:
339+
self.child_nodes.remove(new_child)
340+
repl_index = self.child_nodes.index(old_child)
341+
self.child_nodes[repl_index] = new_child
342+
new_child._set_parent_node(self)
343+
return old_child
344+
304345
def append_child(self, new_child: _AnyNode) -> _AnyNode:
305346
"""Adds the node `new_child` to the end of the list of children of this node.
306347

0 commit comments

Comments
 (0)