DomDocument removeChild in foreach reindexing the dom

前端 未结 4 1367
梦毁少年i
梦毁少年i 2021-01-18 11:25

I am trying to delete p tags with data-spotid attribute

        $dom = new DOMDocument();
        @$dom->loadHTML($description);         


        
4条回答
  •  甜味超标
    2021-01-18 12:02

    ( Assuming that the $dom contains the (DOM) paragraphs you need to filter out ). Let's try some good old JavaScript:

    $ptag = $dom.all.tags("p");
    $ptag = [].slice.call($ptag);
    $i = 0; 
    while($ptag[$i]){
    'data-spotid' in $ptag[$i].attributes ? $ptag[$i++].outerHTML = "" : 0
    }
    

    NOTE: I'm using outerHTML to destroy unwanted elements to avoid calling its parent and relocating the node of interest we already have. Recent Firefox versions are finally supporting it (11+).MDN ref

    I'm also using the brief all.tags() syntax for brevity; Firefox might not be supporting it yet, so you might want to fall back to 'getElementsByTagName()' call there.

提交回复
热议问题