Deleting Elements from DOM without Reloading
In PHP, when you've loaded an HTML document into a DOMDocument object, you may need to remove certain elements. This can be achieved without creating a new DOMDocument altogether.
Sample Code:
<code class="php">$dom = new DOMDocument('1.0', 'utf-8'); $dom->loadHTML($html); foreach ($dom->getElementsByTagName('a') as $href) { if ($href->nodeValue == 'First') { // Delete the element $href->parentNode->removeChild($href); } }</code>
Explanation:
The code iterates through the anchor elements () within the loaded HTML document. For each element, it checks if the nodeValue (text content) within it matches "First". If so, it retrieves the parent node of the current element and calls the removeChild() method on it.
This effectively removes the selected element from the DOM without reloading the entire document.
Additional Notes:
Related questions:
The above is the detailed content of How do you delete elements from the DOM in PHP without reloading the document?. For more information, please follow other related articles on the PHP Chinese website!