duandan9680 2018-10-12 14:35
浏览 86

如何删除没有属性的div标签; 在保持内在HTML的同时?

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 );
        }

    }

}
  • 写回答

1条回答 默认 最新

  • duanlan2003 2018-10-12 15:40
    关注

    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>
    
    评论

报告相同问题?

悬赏问题

  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥15 请问Lammps做复合材料拉伸模拟,应力应变曲线问题
  • ¥30 python代码,帮调试
  • ¥15 #MATLAB仿真#车辆换道路径规划
  • ¥15 java 操作 elasticsearch 8.1 实现 索引的重建
  • ¥15 数据可视化Python
  • ¥15 要给毕业设计添加扫码登录的功能!!有偿
  • ¥15 kafka 分区副本增加会导致消息丢失或者不可用吗?
  • ¥15 微信公众号自制会员卡没有收款渠道啊