I'd like to use PHP DOM Document to remove div
tags which do not contain any attributes. However, I'd like to be able to keep all inner HTML contents.
Example:
<div>
<div>
<div id="test">
Testing...
</div><!-- end #test -->
</div>
</div>
Result:
<div id="test">
Testing...
</div><!-- end #test -->
Here's what I was thinking, but can't seem to get this to do what I want. This method seems to be deleting everything instead of the <div>
tags with no attributes.
# Remove blank div wraps
if ( $div_tags = $dom->getElementsByTagName( 'div' ) ) {
$blank_divs = array();
foreach ( $div_tags as $div_tag ) {
if ( ! $div_tag->hasAttributes() ) {
$blank_divs[] = $div_tag;
}
}
if ( ! empty( $blank_divs ) ) {
foreach ( array_reverse( $blank_divs ) as $blank_div ) {
$blank_div->parentNode->removeChild( $blank_div );
}
}
}
If you know how many iterations you need to remove, you can do the following:
var icount = 2; // number of iterations.
for(i=0; i<icount; i++){
var innerElement = $("#test").contents();
$("#test").replaceWith(innerElement );
}
If you don't know your itterstion you just have to have an identifiable parent such as this:
<div id="container">
<div>
<div id="test">
Testing...
</div><!-- end #test -->
</div>
</div>
<script>
var innerElement = $("#test").contents();
$("#container").replaceWith(innerElement );
</script>