jQuery – setting an element’s text only without removing other element (anchor)

Neal’s answer is my suggestion. jQuery doesn’t have a way to select text nodes How do I select text nodes with jQuery?.

Changing your HTML structure will make for the simplest code. If you can’t do it, you can just use the childNodes property looking for nodes of type 3 (TEXT_NODE)

Here’s some sample code that assumes the last node is the node you want to edit. This is a better approach than replacing the entire contents of the td because you could lose event handlers when you recreate the HTML

$('a').click(() => console.log('<a> was clicked'))

$('#btn').click(() =>
  $('.someClass').get(0).lastChild.nodeValue = " New Value");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="someClass">
  <a href="https://stackoverflow.com/questions/6156470/javascript:void(0)">anchor</a> [ some text ]
</div>

<button id='btn'> Change text without losing a tag's handler</button>

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)