note 48875 deleted from function.dom-domnode-replacechild by didou

From: Date: Sat, 02 Apr 2005 22:46:15 +0000
Subject: note 48875 deleted from function.dom-domnode-replacechild by didou
References: 1  Groups: php.notes 
Request: Send a blank email to php-notes+get-87377@lists.php.net to get a copy of this message
Note Submitter: roland dot swingler at transversal dot com ---- If you are trying to replace more than one node at once, you have to be careful about iterating over the DOMNodeList. If the old node has a different name from the new node, it will be removed from the list once it has been replaced. If you try and do something like: <?php $nodeList = $domObject->getElementsByTagName('nodeName'); // either this ... foreach ($nodeList as $oldNode){ // Replace $oldNode with a new node } // or this ... for ($i = 0; $i < $nodeList->length; $i++){ // Replace $oldNode with a new node } ?> It will miss some of the nodes out, because the the counter is being incremented AND the list is being shortened. However, if you do this: <?php while ($nodeList->length > 0){ // Replace $oldNode with a new node } ?> It will get stuck in an infinite loop if any of the nodes you are replacing have the same name. Therefore you need to use a looping structure like this: <?php $nodeList = $domObject->getElementsByTagName('nodeName'); $i = 0; while ($i < $nodeList->length){ $oldNode = $nodeList->item($i); $newNode = $whatever; // Get your new node from wherever you want if ($oldNode->nodeName == $newNode->nodeName){ $i++ // Only increment counter if the nodes have the same name. } // Now replace the node as shown in the posts below. $importedNode = $domObject->importNode($newNode, true); $oldNode->parentNode->replaceChild($importedNode, $oldNode); }

« previous php.notes (#87377) next »