简体   繁体   English

如何删除所有空跨度<div> ?

[英]How to remove all empty spans in <div>?

I need to remove all empty spans from one of div.我需要从 div 之一中删除所有空跨度。 The problem is, once forEach loop is done, previously not empty spans are empty now so I thought I could use while loop but it seems to loop itself.问题是,一旦 forEach 循环完成,以前不是空的跨度现在是空的,所以我想我可以使用 while 循环,但它似乎是循环自身。 What did I do wrong?我做错了什么?

 function removeEmptySpans() { const tree = document.getElementById('tree') const spans = Array.from(tree.querySelectorAll("span")) let emptySpansExist = true while (emptySpansExist) { emptySpansExist = false spans.forEach(span => { if (span.innerHTML === "") { span.remove() console.log("empty span") emptySpansExist = true } else { console.log("not empty span") } }) } }
 <div id="tree" onClick={removeEmptySpans}> <span> <span> <span></span> </span> <span> <span></span> <span><span></span><span></span></span> <span><span></span>content</span> </span> </span> <span></span> </div>

 function removeEmptySpans() { const tree = document.getElementById('tree'); const spans = Array.from(tree.querySelectorAll("span")).reverse(); for(let i=0; i<spans.length; i++) { if (spans[i].innerHTML.trim() === "") { // console.log(i, spans[i], spans[i].innerHTML, "---"); spans[i].remove(); } } } removeEmptySpans(); console.log('Remaining spans:', tree.querySelectorAll("span").length);
 <div id="tree" onClick="removeEmptySpans()"> <span> <span> <span></span> </span> <span> <span></span> <span><span></span><span></span></span> <span><span></span>content</span> </span> </span> <span> </span> </div>

The code makes a list of all the possible spans inside the tree element.该代码列出了树元素内所有可能的跨度。

The query selector will build a forward list but to avoid having conflicts you just need to reverse the list so you can get the empty children removed first and avoid removing a parent having different spans which some of are filled of content.查询选择器将构建一个前向列表,但为避免发生冲突,您只需反转列表,这样您就可以首先删除空的子节点,并避免删除具有不同跨度的父节点,其中一些填充了内容。

The trim method in the conditional statement allows you to remove all the empty spaces at the prefix and suffix of your innerHTML to avoid confusing the functions with spaces only.条件语句中的trim方法允许您删除 innerHTML 前缀和后缀处的所有空格,以避免将函数与仅空格混淆。

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

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