Presented with a particular HTML snippet, you seek to eliminate a portion enclosed within a specific
Harnessing the power of Document Object Model (DOM), you can devise a surgical excision of the targeted section. This approach permits comprehensive manipulation of HTML structures.
<code class="php"><?php $dom = new DOMDocument; $dom->loadHTML($htmlString); $xPath = new DOMXPath($dom); $nodes = $xPath->query('//*[@id="anotherDiv"]'); if($nodes->item(0)) { $nodes->item(0)->parentNode->removeChild($nodes->item(0)); } echo $dom->saveHTML(); ?></code>
In the provided code snippet, we first load the HTML string into a DOMDocument instance. Subsequently, we employ a DOMXPath object to pinpoint the element with the designated id attribute. If the element exists, we eliminate it and its descendants using the removeChild() method. The processed HTML is then extracted and displayed.
The above is the detailed content of How to Remove a Specific HTML `` Tag and Its Contents Using Its Identifier?. For more information, please follow other related articles on the PHP Chinese website!