Home  >  Article  >  Backend Development  >  How to Delete Elements from a DOMDocument in PHP Without Creating a New Document?

How to Delete Elements from a DOMDocument in PHP Without Creating a New Document?

Linda Hamilton
Linda HamiltonOriginal
2024-11-02 02:48:02986browse

How to Delete Elements from a DOMDocument in PHP Without Creating a New Document?

Deleting Elements from DOMDocument

It's often necessary to manipulate the content of HTML documents loaded with DOMDocument. One common task is to remove elements from the DOM.

Consider the following 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</code>

How can the First element be removed from the DOM without creating a new document?

Solution

To remove a node, instruct the parent node to remove the child:

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

Refer to the $parentNodeDocs property of DOMNode and removeChild()Docs method for further details.

Related Questions

  • How to remove attributes using PHP DOMDocument?
  • How to remove an HTML element using the DOMDocument class

The above is the detailed content of How to Delete Elements from a DOMDocument in PHP Without Creating a New Document?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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