Home > Backend Development > PHP Tutorial > How to Remove Specific HTML Content Based on ID Using Native DOM?

How to Remove Specific HTML Content Based on ID Using Native DOM?

DDD
Release: 2024-10-26 06:08:31
Original
468 people have browsed it

How to Remove Specific HTML Content Based on ID Using Native DOM?

Removing Inner HTML Content Based on ID

This guide demonstrates how to remove specific HTML content enclosed within a tag identified by its ID, effectively stripping away undesired sections of a web page.

Problem Statement

Consider the following HTML:

<code class="html"><html>
    <body>
        bla bla bla bla
        <div id="myDiv">
            more text
            <div id="anotherDiv">
                And even more text
            </div>
        </div>
        bla bla bla
    </body>
</html></code>
Copy after login

The aim is to remove everything starting from the

tag, including its closing
.

Native DOM Solution

Using the native DOM (Document Object Model), you can achieve this as follows:

<code class="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>
Copy after login

This code initializes a DOMDocument object, loads the HTML into it, and creates an XPath object to query based on the specified ID. It then finds the corresponding node and removes it from its parent, effectively stripping away the unwanted HTML content.

The above is the detailed content of How to Remove Specific HTML Content Based on ID Using Native DOM?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template