参见英文答案 >
How to remove only the parent element and not its child elements in JavaScript?11个
任何人都可以帮助我如何在不删除JavaScript内容的情况下删除div标签?
任何人都可以帮助我如何在不删除JavaScript内容的情况下删除div标签?
<div id="id1" class="someclass"> <p>some text <label> Test content </label> </p> <div id="id2" style="overfolw:scroll"> <span>some text</span> <div id="level3"> <label> Test content </label> <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a> </div> </div> </div>
预期输出如下所示.
<p>some text <label> Test content </label> </p> <span>some text</span> <label> Test content </label> <a href=https://twitter.com/realDonaldTrump/status/882186896285282304 target=_blank rel=noopener>creepiness</a>
解决方法
1.使用纯java脚本: –
var divs=document.getElementsByTagName('div'); var counter = divs.length-1; for(i=counter;i>=0;i--){ divs[i].outerHTML = divs[i].innerHTML; }
<div id="id1" class="someclass"> <p>some text <label> Test content </label> </p> <div id="id2" style="overfolw:scroll"> <span>some text</span> <div id="level3"> <label> Test content </label> <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a> </div> </div> </div>
你也可以使用jQuery unwrap(): –
$(document).ready(function(){ $('div').contents().unwrap(); });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="id1" class="someclass"> <p>some text <label> Test content </label> </p> <div id="id2" style="overfolw:scroll"> <span>some text</span> <div id="level3"> <label> Test content </label> <a href="https://twitter.com/realDonaldTrump/status/882186896285282304" target=_blank rel=noopener>creepiness</a> </div> </div> </div>