note 49945 modified in function.dom-domnode-removechild by didou
| From: | didou@php.net | Date: | Sat, 02 Apr 2005 22:35:17 +0000 |
| Subject: | note 49945 modified in function.dom-domnode-removechild by didou | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-87374@lists.php.net to get a copy of this message | ||
For those who don't understand >sbeam at onsetcorps dot net on 02-Feb-2005 12:07<
'hack', here's a little discussion:
First but *wrong* try would be:
<?php
foreach ($parent->childNodes as $child) {
$parent->removeChild($child);
?>
This doesn't work because DOM tree id modified on-the-fly and this confuses foreach loop.
The idea behind sbeam's trick is that after removing the first item in the first iteration, the
second item in childNodes nodelist immediately becomes the first item. That's why we must
_always_ remove the first child. Here's another implementation:
<?php
$count = $parent->childNodes->length;
for ($i = 0; $i < $count; $i++) {
$oldNode = $parent->removeChild($parent->childNodes->item(0)); // !!! not item($i) !!!
}
?>
--was--
For those who dont understand >sbeam at onsetcorps dot net on 02-Feb-2005 12:07< hack,
heres a little discussion:
First but *wrong* try would be:
<?php
foreach ($parent->childNodes as $child) {
$parent->removeChild($child);
?>
This doesnt work because DOM tree id modified on-the-fly and this confuses foreach loop.
The idea behind sbeams trick is that after removing the first item in the first iteration, the
second item in childNodes nodelist immediately becomes the first item. Thats why we must _always_
remove the first child. Heres another implementation:
<?php
$count = $parent->childNodes->length;
for ($i = 0; $i < $count; $i++) {
$oldNode = $parent->removeChild($parent->childNodes->item(0)); // !!! not item($i) !!!
}
?>
http://php.net/manual/en/function.dom-domnode-removechild.php