I have a DomElement in PHP. I want to remove some specific styles from style attribute of the Element and all Childrens of it. I know that it should be recursive.
For example I have:
<a href="" style="top:10px;left:4px;margin:4px"><img style="top:3px"/></a>
And I remove top
style. It converts to:
<a href="" style="left:4px;margin:4px"><img style=""/></a>
Try below code using JQUERY
$( document ).ready(function() {
$('a *').css('top',''); // For Remove specific property of child element
$('a').css('top',''); // For Remove specific property of element
});
Use the function below for the parent node:
private function prevent_html_style_properties($element){
if($element->nodeType != XML_ELEMENT_NODE)
return $element;
$element->removeAttribute('class');
if($element->hasAttribute('style')){
$style = $element->getAttribute('style');
$existingDeleteAttrList = array();
$attrList = [
'height',
'position',
'top'];
$style_parts = explode(';', $style);
foreach($attrList as $attr){
if(strpos($style, $attr) !== false)
$existingDeleteAttrList[] = $attr;
}
$new_attr_value = '';
foreach($style_parts as $style_part){
$attr_is_safe = true;
foreach($existingDeleteAttrList as $attr){
if(strpos($style_part, $attr) !== false) {
$attr_is_safe = false;
break;
}
}
if($attr_is_safe)
$new_attr_value .= $style_part . ';';
}
$element->setAttribute('style', $new_attr_value);
}
$children = $element->childNodes;
foreach ($children as $child)
{
$element->replaceChild($this->prevent_html_tag_styles($child), $child);
}
return $element;
}
Usage:
$element = $this->prevent_html_style_properties($element);
Some Explanation:
XML_ELEMENT_NODE
.replaceChild
to fix for its direct children, and so on.