[英]How do you remove text without affecting child elements?
我有一個帶子div的div以及一些文本。 我想使用jQuery / JS保留子div並刪除文本。
<div id="parent">
<div>keep this</div>
<div>keep this</div>
Some random text that can't be predicted (to be removed)
<div>keep this</div>
</div>
您可以使用TreeWalker查找作為根元素直接子級的所有文本節點並將其刪除。
function removeChildTextNodes(root) { var treeWalker = document.createTreeWalker(root, NodeFilter.SHOW_ALL, { acceptNode: function(node) { if(node.nodeType === 3) return NodeFilter.FILTER_ACCEPT }, }, true); var currentNode = treeWalker.firstChild(); while(currentNode) { var removedNode = treeWalker.currentNode; currentNode = treeWalker.nextNode() removedNode.remove(); } } var root = document.querySelector('#parent'); removeChildTextNodes(root);
<div id="parent"> <img /> Some random text that can't be predicted (to be removed) <div>keep this</div> Some random text that can't be predicted (to be removed) <h2> keep this </h2> Some <strong>random</strong> text that can't be predicted (to be removed) <a>keep this</a> </div>
使用Javascript
您只需獲取id=parent
的元素的所有childNodes ,然后遍歷這些id=parent
即可.remove()那些具有nodeType等於Node.TEXT_NODE的子節點 :
let childs = document.getElementById("parent").childNodes; childs.forEach(c => c.nodeType === Node.TEXT_NODE && c.remove());
<div id="parent"> <div>keep this</div> <div>keep this</div> Some random text that can't be predicted (to be removed) <div>keep this</div> </div>
或者,也可以使用JQuery.contents()使用下一種方法:
$("#parent").contents().each(function() { if (this.nodeType === Node.TEXT_NODE) this.remove(); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div id="parent"> <div>keep this</div> <div>keep this</div> Some random text that can't be predicted (to be removed) <div>keep this</div> </div>
使用jQuery的解決方案
$('.parent') // Return direct descendants. This also returns text nodes, as opposed to children() .contents() // Target text nodes only .filter(function() { return this.nodeType === Node.TEXT_NODE; }).remove();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="parent"> <div>keep this</div> <div>keep this</div> Some random text that can't be predicted (to be removed) <div>keep this</div> </div> <div class="parent"> Some random text in another location <div>keep this</div> <div>keep this</div> <div>keep this</div> More random text </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.