首页 > 解决方案 > 删除元素后的所有内容,包括文本

问题描述

我需要一个看似简单的快速解决方案:

我想在 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。

标签: javascriptjquery

解决方案


从父节点中删除最后一个节点,直到您想要的节点成为父节点的最后一个节点。

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>


推荐阅读