From f201e110cb8127579fabed36d8d390d87d68d520 Mon Sep 17 00:00:00 2001 From: Joshua Graham Date: Fri, 18 Feb 2022 18:35:11 +1100 Subject: [PATCH] Make DomQuery sets unique, so parent() doesn't return 2 parents() for the two children sharing the same parent. --- src/Rct567/DomQuery/DomQueryNodes.php | 19 +++++++++++++++++++ 1 file changed, 19 insertions(+) diff --git a/src/Rct567/DomQuery/DomQueryNodes.php b/src/Rct567/DomQuery/DomQueryNodes.php index 0189221..0aedf78 100644 --- a/src/Rct567/DomQuery/DomQueryNodes.php +++ b/src/Rct567/DomQuery/DomQueryNodes.php @@ -267,6 +267,25 @@ public function loadDomNodeList(\DOMNodeList $dom_node_list) */ public function addDomNode(\DOMNode $dom_node, $prepend=false) { + // If the node already exists, remove it so it be added again. + // Ideally the element order is document order after the duplicates are + // added, like real jQuery. + $this->nodes = call_user_func( + function (array $existing_nodes, \DOMNode $dom_node) { + foreach ($existing_nodes as $array_id => $existing_node) { + if ($existing_node->isSameNode($dom_node)) { + unset($existing_nodes[$array_id]); + // Reset array keys, optional. + $existing_nodes = array_values($existing_nodes); + // Break for performance. + break; + } + } + return $existing_nodes; + }, + $this->nodes, + $dom_node + ); if ($prepend) { array_unshift($this->nodes, $dom_node); } else {