How can I change the name of an element in DOM?

后端 未结 3 1618
感情败类
感情败类 2020-12-01 18:53

In PHP with DOM, I have a DomElement object which represents an element.

I have one case where I need to change this so its element name is

3条回答
  •  孤城傲影
    2020-12-01 19:40

    Could you use importNode() to copy the childNodes of your element to a newly created element?

    function changeName($node, $name) {
        $newnode = $node->ownerDocument->createElement($name);
        foreach ($node->childNodes as $child){
            $child = $node->ownerDocument->importNode($child, true);
            $newnode->appendChild($child, true);
        }
        foreach ($node->attributes as $attrName => $attrNode) {
            $newnode->setAttribute($attrName, $attrNode);
        }
        $newnode->ownerDocument->replaceChild($newnode, $node);
        return $newnode;
    }
    
    $domElement = changeName($domElement, 'person');
    

    Perhaps something like that would work, or you could try using cloneChild().

    Edit: Actually, I just realized that the original function would lose the placement of the node. As per the question thomasrutter linked to, replaceChild() should be used.

提交回复
热议问题