我有一个带有子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>
答案 0 :(得分:1)
您可以使用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>
答案 1 :(得分:1)
按Javascript
,您只需用id=parent
获得元素的所有childNodes,然后遍历这些孩子到.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>
答案 2 :(得分:0)
使用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>