javascript - 删除元素后的所有内容,包括文本
问题描述
我需要一个看似简单的快速解决方案:
我想在 html 元素中的特定元素之后删除所有内容,包括文本。
我有 :
<div class="main-container">
Some text and <a href="" class="classone">SOME HTML</a>.
I also have someother text, and some more <b>html</b>
</div>
我想删除该主容器中“classone”元素之后的所有内容。
我已经尝试过$('.main-container').nextAll().remove();
,但这仅删除了 html。
解决方案
从父节点中删除最后一个节点,直到您想要的节点成为父节点的最后一个节点。
function removeAllNodesAfter (node) {
const parentNode = node.parentNode;
while (parentNode.lastChild !== node) {
parentNode.removeChild(parentNode.lastChild);
}
};
removeAllNodesAfter($('.classone')[0]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="main-container">
Some text and <a href="" class="classone">SOME HTML</a>.
I also have someother text, and some more <b>html</b>
</div>
推荐阅读
- java - Problem with javafx application resulting in "cannot be resolved" error messages?
- javascript - For some reason I am getting: fetch(...).then(...).then(...).map is not a function
- javascript - How to update data on a react app from python?
- linux - parrot os 4.7 升级失败
- r - 如何在R中求解非线性联立二次方程
- javascript - 用 Puppeteer 抓取下拉菜单而不抓取子菜单的最佳方法是什么?
- java - 只显示启动画面
- c# - 形状类的正确层次结构
- python - 给定代码中的 SQL 注入漏洞在哪里以及如何使用 python 和 sqlite 来利用它
- python - python索引问题“超出范围”