Reputation: 4472
I have an element like this:
<td>
<a>anchor</a>
[ some text ]
</td>
And i need to set it's text in jQuery, without removing the anchor.
The element's contents could vary in order (text before or after), and the actual text is unknown.
Thanks
New Update
This is what i came up using, assumes only a single text node:
function setTextContents($elem, text) {
$elem.contents().filter(function() {
if (this.nodeType == Node.TEXT_NODE) {
this.nodeValue = text;
}
});
}
setTextContents( $('td'), "new text");
Upvotes: 38
Views: 27467
Reputation: 31
After this topic I make some improvement, nothing deal. Because if you get a long script and then the selector is not there the nodeValue return TypeError and stop the script on that line, so I use the show() basic effect into a function to execute if that element exists on DOM, then if is true use nodeValue to change it (I am noob on java so mabye this not
$('td').show(function() {
$(this).contents()[0].nodeValue = "new text"
});
Upvotes: 0
Reputation: 92304
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="javascript:void(0)">anchor</a> [ some text ]
</div>
<button id='btn'> Change text without losing a tag's handler</button>
Upvotes: 49
Reputation: 36619
Without changing markup:
var anchor = $('td').find('a').clone();
$('td').text('{ some other text }').prepend(anchor);
Upvotes: 4
Reputation: 146310
If it is possible to put the text in a span:
<td id='someID'>
<a>anchor</a>
<span>[ some text ]</span>
</td>
You can do:
$('td#someID span').text('new text')
Upvotes: 11