jquery - 使用 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>
解决方案
没有我想的那么简单。我正在使用内容和测试
可能可以使用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>
推荐阅读
- r - 无法在 for 循环中创建列并更改其值
- c# - 如何将 Web API(已部署 IIS)连接到 MSSQLLocalDB
- node.js - 如果使用 chai-sies / Mocha / Test 调用函数(节点模块),如何测试它
- html - 如何从我的 iframe 中获取点击监听器?
- mysql - 根据列和状态列的组合查询以获取记录
- unity3d - 加载我的场景时发生未知错误。统一
- automation - 如何使用 VBS 捕获命令窗口的输出并通过播放的声音通知用户?
- preview - 使用 azure Form Recognizer api v2.1 通过 REST 训练模型时提供自定义模型名称
- mysql - MySql查询不同的条件
- php - 从 MySQL 填充数据表中的数据:Php Ajax