note 48875 added to function.dom-domnode-replacechild

From: Date: Mon, 10 Jan 2005 12:21:27 +0000
Subject: note 48875 added to function.dom-domnode-replacechild
Groups: php.notes 
Request: Send a blank email to php-notes+get-83040@lists.php.net to get a copy of this message
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); } ---- Manual Page -- http://www.php.net/manual/en/function.dom-domnode-replacechild.php Edit -- http://master.php.net/manage/user-notes.php?action=edit+48875 Delete -- http://master.php.net/manage/user-notes.php?action=delete+48875&report=yes Reason: bad code -- http://master.php.net/manage/user-notes.php?action=delete+48875&report=yes&reason=bad+code Reason: spam -- http://master.php.net/manage/user-notes.php?action=delete+48875&report=yes&reason=spam Reason: useless example -- http://master.php.net/manage/user-notes.php?action=delete+48875&report=yes&reason=useless+example Reason: contains commercial links -- http://master.php.net/manage/user-notes.php?action=delete+48875&report=yes&reason=contains+commercial+links Reason: useless note -- http://master.php.net/manage/user-notes.php?action=delete+48875&report=yes&reason=useless+note Reject -- http://master.php.net/manage/user-notes.php?action=reject+48875&report=yes Search -- http://master.php.net/manage/user-notes.php

« previous php.notes (#83040) next »