Home > Backend Development > PHP Tutorial > Can You Delete Elements in a Loaded DOMDocument Without Creating a New One?

Can You Delete Elements in a Loaded DOMDocument Without Creating a New One?

Susan Sarandon
Release: 2024-10-31 01:49:02
Original
847 people have browsed it

 Can You Delete Elements in a Loaded DOMDocument Without Creating a New One?

Deleting Elements with DOMDocument

Manipulating HTML documents is a common task for web developers. In PHP, the DOMDocument class provides a convenient way to parse and manipulate HTML code. While it's possible to create a new DOMDocument from scratch, in many cases it's more efficient to load an existing document into a DOMDocument object.

One of the most common operations when modifying an HTML document is removing elements. Let's consider the following HTML code:

<code class="html"><p><a href="#">First</a></p>
<p><a href="#">Second</a></p>
<p><a href="#">Third</a></p></code>
Copy after login

Q: Is it possible to delete an element in a loaded DOMDocument without creating a new one?

<code class="php">$dom = new DOMDocument('1.0', 'utf-8');
$dom->loadHTML($html);

foreach ($dom->getElementsByTagName('a') as $href) {
    if ($href->nodeValue == 'First')
        // delete
}</code>
Copy after login

A: Yes, it is possible to delete an element from a loaded DOMDocument without creating a new one:

<code class="php">$href->parentNode->removeChild($href);</code>
Copy after login

This approach modifies the original DOMDocument object directly. The DOMNode::$parentNode property references the parent node of the current node, and the DOMNode::removeChild() method removes the specified child node from the parent node.

Additional resources for working with DOMDocuments:

  • [DOMNode::$parentNode Documentation](https://www.php.net/manual/en/domnode.parentnode.php)
  • [DOMNode::removeChild() Documentation](https://www.php.net/manual/en/domnode.removechild.php)
  • How to remove attributes using PHP DOMDocument?
  • How to remove an HTML element using the DOMDocument class

The above is the detailed content of Can You Delete Elements in a Loaded DOMDocument Without Creating a New One?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template