I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.
For instance:
Some
An alternative way would be to use the contents()
method as follows:
Given
<a href="link.html">Some text <img src="image.jpg" /></a>
you can replace 'Some text'
with jQuery
var text = $('a').contents().first()[0].textContent;
$('a').contents().first()[0].textContent = text.replace("Some text", "Other text");
jsFiddle example here.
The idea of contents()
was inspired by this question, answered by user charlietfl.
just use some plain js functionality:
$('a')[0].firstChild.nodeValue = "New Text";