0

I have a paragraph tag with some text and an anchor within it. How would I remove just the text and not the anchor link? I've looked into .innerHTML, but I can't mess with the anchor link because it's href value is dynamically generated.

<p>Text to be removed <a href="blahrdyblahr">Link Text</a></p>
lowbelly
  • 103
  • 3
  • 9
  • Possible duplicate of [How to remove text (without removing inner elements) from a parent element using jquery](https://stackoverflow.com/questions/11633610/how-to-remove-text-without-removing-inner-elements-from-a-parent-element-using) – Obsidian Age May 10 '18 at 22:28

4 Answers4

4

children() returns all direct descendants of the element that are not text nodes.

$('p').html(function(){
  return $(this).children();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Text to be removed <a href="blahrdyblahr">Link Text</a></p>
<p><a href="blahrdyblahr">Link Text</a> Text to be removed</p>
Taplar
  • 24,788
  • 4
  • 22
  • 35
3

Remove the text from the textNode itself (which is the first child).

document.querySelector('p').firstChild.textContent = '';
<p>Text to be removed <a href="blahrdyblahr">Link Text</a></p>
Randy Casburn
  • 13,840
  • 1
  • 16
  • 31
0

Just to give another option (and try to release myself from the guilt of misunderstanding the question)

$('p').contents().not($('p').children()).remove()

This will remove text and comment nodes.

.contents() returns al the children including text and comment nodes, so we used the .not() function to exclude the .children() since children won't contain the text node, leaving only the text and comment nodes to be removed.

Here's the fiddle: https://jsfiddle.net/aL7cmmjd/

See here: https://api.jquery.com/contents/

AarónBC.
  • 1,280
  • 9
  • 14
0

Iterate over tag's children and remove text nodes:

const container = document.querySelector('p');

for (let i = 0; i < container.childNodes.length; ++i) {
  if (container.childNodes[i].nodeType === Node.TEXT_NODE) {
    container.removeChild(container.childNodes[i]);
  }
}
<p>Text to be removed <a href="blahrdyblahr">Link Text</a></p>