我需要一个快速解决方案的东西看似简单:
我想去除一切,包括文本,在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。
你可能会利用.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
。如果有一个更好的解决办法,我随时欢迎。这是我想出了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>
从父节点删除最后一个节点,直到你想要的节点成为父节点的最后一个节点。
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>
下面是使用无环路的解决方案:
$(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>