user4385532
user4385532

Reputation:

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:

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 was likely inserted into this div via document.getElementById('blah').appendChild(document.createTextNode('Lorem...'))

Upvotes: 4

Views: 784

Answers (2)

D Lowther
D Lowther

Reputation: 1619

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.

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>

Upvotes: 0

j08691
j08691

Reputation: 208002

You can use nextsibling to target the text node and remove it.

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>

Upvotes: 1

Related Questions