简体   繁体   English

如何从节点中删除文本?

[英]How do I remove text from a node?

<div id="blah">
    <img src="yadda.svg" />
    <span>
        Text of great importance
    </span>
    Lorem ipsum dolor sit amet
</div>

Now I know I can easily clear #blah from all content: 现在我知道我可以轻松地从所有内容中清除#blah

for (let node of Array.from(document.getElementById('blah').childNodes))) node.remove()

But I only want to get rid of all text (in this case Lorem ipsum... ) I do not want to get rid of the image nor of the span nor of the text of the span. 但我只想摆脱所有文本(在这种情况下Lorem ipsum... )我不想摆脱图像,也不想跨度和跨度文本。

Lorem was likely inserted into this div via document.getElementById('blah').appendChild(document.createTextNode('Lorem...')) Lorem可能通过document.getElementById('blah').appendChild(document.createTextNode('Lorem...'))插入到这个div document.getElementById('blah').appendChild(document.createTextNode('Lorem...'))

This solution is super brittle and I don't honestly recommend it, but if your html is exactly that format always then this does work. 这个解决方案非常脆弱,我并不诚实地推荐它,但如果你的html完全是那种格式,那么这确实有效。

 const wrapper = document.querySelector('#blah'); const stripped = Array.from(wrapper.children).reduce((a, c) => a + c.outerHTML, ''); wrapper.innerHTML = stripped; 
 <div id="blah"> <img src="yadda.svg" /> <span> Text of great importance </span> Lorem ipsum dolor sit amet </div> 

You can use nextsibling to target the text node and remove it. 您可以使用nextsibling来定位文本节点并将其删除。

 document.querySelector('#blah > span').nextSibling.remove() 
 <div id="blah"> <img src="yadda.svg" /> <span> Text of great importance </span> Lorem ipsum dolor sit amet </div> 

 var btn = document.getElementById('btn'); btn.addEventListener('click', function(e) { var blahElem = document.getElementById('blah'); var content = ''; for(var i=0;i<blahElem.childElementCount;i++){ content += blahElem.children[i].outerHTML; } blahElem.innerHTML = content; }); 
 <div id="blah"> <img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.png?v=c78bd457575a" /> <span> Text of great importance </span> Lorem ipsum dolor sit amet </div> <br/> <hr/> <button id="btn">remove 'Lorem ipsum'</button> 

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

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