pedmillon pedmillon - 4 months ago 18
jQuery Question

jQuery string replacement and a link

I replace text inside table cells using text.replace

$('td:contains("ABC ")').text(function(_, text) {
return text.replace(/ABC /g, 'XYZ');
return text.replace('ABC ', 'XYZ');
});


for such a cell
ABC <a href="http://example.com">Text</a></td>


For some reason when I apply that replacement, the links inside the cells become inactive to mouse click. What's the cause and is it possible to change that?

Answer

Replace only the text node:

$('td:contains("ABC ")').contents().filter(function() {
    return this.nodeType == 3;
}).each(function() {
    this.textContent = this.textContent.replace(/ABC /g, 'XYZ');
});

Reference