Reputation: 103
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>
Upvotes: 0
Views: 64
Reputation: 1330
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/
Upvotes: 0
Reputation: 114
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>
Upvotes: 0
Reputation: 24965
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>
Upvotes: 4
Reputation: 14165
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>
Upvotes: 3