6

Is there a way to create my own DOMNodeList? E.g.:

$doc = new DOMDocument(); 
$elem = $doc->createElement('div');
$nodeList = new DOMNodeList; 
$nodeList->addItem($elem); // ?

My idea is to extend DOMDocument class adding some useful methods that return data as DOMNodeList.

Is it possible to do it without writing my own version of DOMNodeList class?

optimizitor
  • 807
  • 13
  • 18

1 Answers1

3

You cannot add items to DOMNodeList via it's public interface. However, DOMNodeLists are live collections when connected to a DOM Tree, so adding a Child Element to a DOMElement will add an element in that element's child collection (which is a DOMNodeList):

$doc = new DOMDocument();
$nodelist = $doc->childNodes; // a DOMNodeList
echo $nodelist->length;       // 0

$elem = $doc->createElement('div');
$doc->appendChild($elem);

echo $nodelist->length;       // 1

You say you want to add "some useful methods that return data as DOMNodeList". In the context of DOMDocument, this is what XPath does. It allows you to query all the nodes in the document and return them in a DOMNodeList. Maybe that's what you are looking for.

Gordon
  • 312,688
  • 75
  • 539
  • 559
  • Thank you for the answer, it solves the problem. I'm working on a mini-library prototype that adds CSS-support to DOMDocument class. It performs specific tasks like finding the visible background-color of an image with transparency (through accessing the CSS of its element and parent nodes). I'll try out XPath, once I've found a decent converter of CSS selectors to XPath. – optimizitor Nov 29 '14 at 09:57
  • @optimizitor note that there is 3rd party libraries out there that already have that. See http://stackoverflow.com/a/3577662/208809 – Gordon Nov 29 '14 at 10:00
  • Let's say, the `DOMNode $elem` is taken from the loaded HTML, is there a way to save its context (`parentNode`, `previousSibling`, `nextSibling`)? It changes when `DOMNode::appendChild(DOMNode $elem)` is applied. – optimizitor Nov 29 '14 at 14:23
  • @optimizitor not sure I understand. The entire DOM is a live structure. So everything you do (inserting, removing, etc) is immediately reflected in the nodes. – Gordon Nov 29 '14 at 16:27