繁体   English   中英

删除所有内容,包括元素后的文字

[英]Remove Everything including text after an element

我需要快速解决一些看似简单的问题:

我想删除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> 

您可以使用.contents()

 $(function () { var FoundClass = false; $(".main-container").contents().filter(function (s, el) { if ($(el).hasClass("classone")) { FoundClass = true; return false; } return FoundClass; }).remove(); }); 
 <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> 

这有点有点FoundClass因为我使用了标志FoundClass 如果有更好的解决方案,我总是很欢迎。 这就是我想到的jQuery的.contents()

while它们存在于DOM您可以删除.classone .nextSibling

 const one = document.querySelector(".classone"); while (one.nextSibling) one.parentElement.removeChild(one.nextSibling); console.log('done'); 
 <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> 

这是不使用循环的解决方案:

 $(document).ready(function() { 'use strict'; const content = $(".main-container").html(); const element = $(".main-container .classone").html(); const index = content.indexOf(element); $(".main-container").html(content.substr(0, index + element.length)); }); 
 <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> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM