我有以下HTML,我想删除从第一个"a"到表格的所有内容.由于有一些文本不在容器内,我无法弄清楚如何简单地从一个点到另一个点
$('.MyDiv a').nextUntil('.MyDiv table').remove();
$('.MyDiv a').nextUntil('table').remove();Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="MyDiv">
<div>div1</div>
<div>div2</div>
<div>div3</div>
<!- Remove all below ->
<a>a1</a>
<a>a2</a>
<a>a3</a>
<ul><li>ul1</li></ul>
Text with no wrap more text with no wrap
<div>div4</div>
Text with no wrap
<!- Remove all above ->
<table><tr><td>table</td></tr></table>
</div>Run Code Online (Sandbox Code Playgroud)
新的HTML应该是这样的
<div class="MyDiv">
<div>div1</div>
<div>div2</div>
<div>div3</div>
<table><tr><td>table</td></tr></table>
</div>
Run Code Online (Sandbox Code Playgroud)
并不像我想的那么简单.我正在使用内容和测试
可能会使用addBack,但这很容易阅读和工作
var found = false;
$('.MyDiv').contents().each(function() {
// debugging
var whitespace=this.nodeType==3, comment=this.nodeType==8, tag=this.nodeType==1;
if (!whitespace) console.log(tag?this.tagName:"comment",this.textContent);
// end debugging
if (this.tagName=="A") found=true;
if (found) {
// stop at first table - to stop at comment, test nodeType==8 instead
if (this.tagName =="TABLE") {
console.log("stopped");
return false;
}
else $(this).get(0).remove(); // dom / textnodes
}
});Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 3.5em !important; }Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="MyDiv">
<div>d1</div>
<div>d2</div>
<div>d3</div>
<!- Remove all below ->
<a>first a</a>
<a>second a</a>
<a>third a</a>
<ul><li>an LI</li></ul>
Text with no wrap more text with no wrap
<div>d4</div>
Text with no wrap
<!- Remove all above ->
<table><tr><td>Table <a href="">An embedded anchor</a></td></tr></table>
After table
</div>Run Code Online (Sandbox Code Playgroud)