php - Iterate over all DOM elements including added elements

619

I have this method that loops through all nodes:

public function processNode(DOMNode $element){
    if($element instanceof DOMElement){
        foreach($element->childNodes as $node){
            // Adds child nodes and/or modifies the current node
            $this->editNode($node);
            if($node->hasChildNodes()){
                $this->processNode($node);
            }
        }
    }
}

However, I think that when nodes are added within theeditNode() method, this doesn't pick them up and process those nodes as well.

Is there a better way for me to loop through all nodes including nodes that have been added viaeditNode()?

966

Answer

Solution:

It looks like doing afor instead of aforeach is a better way to go. I was then able to process the items that were getting skipped when using theforeach.

public function processNode(DOMNode $element){
    if($element instanceof DOMElement){
        $nodes = $element->childNodes;
        for($i = 0; $i < $nodes->length; $i++){
            $node = $nodes->item($i);
            $this->editNode($node);
            if($node->hasChildNodes()){
                $this->processNode($node);
            }
        }
    }
}

People are also looking for solutions to the problem: PHP/HTML/CSS/FileMaker PHP API Conditional Formatting <td>

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.