Hey so i have a use of a php function that would delete every element of specific type in php. More specifically i want to delete all the labels on my website, e.g:
JavaScript
x
DOMDocument::deleteAllElementsOfType("label");
Any help is appreciated.
Advertisement
Answer
A couple of ways:
With XPath:
JavaScript
<?php
$dom = new DOMDocument();
$dom->loadHtml('
<form>
<label>a</label>
<input />
<label>b</label>
<input />
<label>c</label>
<input />
</form>
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$xpath = new DOMXPath($dom);
foreach ($xpath->query("//label") as $label) $label->parentNode->removeChild($label);
echo $dom->saveHTML();
Result
JavaScript
<form>
<input>
<input>
<input>
</form>
With getElementsByTagName
Due to it being a live document you convert the iterator to an array with iterator_to_array
JavaScript
$dom = new DOMDocument();
$dom->loadHtml('
<form>
<label>a</label>
<input />
<label>b</label>
<input />
<label>c</label>
<input />
</form>
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
foreach (iterator_to_array($dom->getElementsByTagName('label')) as $label) $label->parentNode->removeChild($label);
echo $dom->saveHTML();
Result
JavaScript
<form>
<input>
<input>
<input>
</form>
See it online: https://3v4l.org/WJpqk
You could extend DOMDocument if you want to add your own methods
JavaScript
<?php
class Document extends DOMDocument {
function __construct(string $version = "1.0", string $encoding = "") {
parent::__construct($version, $encoding);
}
public function deleteAllElementsOfType(string $type) {
foreach (iterator_to_array($this->getElementsByTagName($type)) as $item) $item->parentNode->removeChild($item);
}
}
$dom = new Document();
$dom->loadHtml('
<form>
<label>a</label>
<input />
<label>b</label>
<input />
<label>c</label>
<input />
</form>
', LIBXML_HTML_NOIMPLIED | LIBXML_HTML_NODEFDTD);
$dom->deleteAllElementsOfType('label');
echo $dom->saveHTML();