首页 > 解决方案 > 使用 jQuery 删除从这里到这里的所有内容

问题描述

我有以下 HTML,我想删除从第一个“a”到表格的所有内容。由于有些文本不在容器内,我无法弄清楚如何简单地从一个点转到另一个点

$('.MyDiv a').nextUntil('.MyDiv table').remove();
$('.MyDiv a').nextUntil('table').remove();
<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>

新的 HTML 应该是这样的

<div class="MyDiv">
  <div>div1</div>
  <div>div2</div>
  <div>div3</div>
  <table><tr><td>table</td></tr></table>
</div>

标签: jquery

解决方案


没有我想的那么简单。我正在使用内容和测试

可能可以使用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 
  }  
});
.as-console-wrapper { max-height: 3.5em !important; }
<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>


推荐阅读