I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.
For instance:
Some
Wrap the text you want to change in a span
<a href="link.html"><span>Some text</span> <img src="image.jpg" /></a>
$('a span').html( 'new text' );
An efficient and robust way that doesn't require you to know what the inner elements are or what the text is:
var $a = $('a');
var inner = '';
$a.children.html().each(function() {
inner = inner + this.outerHTML;
});
$a.html('New text' + inner);
You can change it by .contents()
$('.yourElement').contents()[0].data = 'New Data';
where in your case the "[0].data" is your text data
I added a jQuery function for that need.
you may need to convert the html-entities to text representation, so i added decodeEntities
function.
function decodeEntities(encodedString) {
if (typeof encodedString != "string") return encodedString;
if (!encodedString) return "";
var textArea = document.createElement('textarea');
textArea.innerHTML = encodedString;
return textArea.value;
}
jQuery.fn.textOnly = function(n) {
if (this.length > 0)
$(this).html(decodeEntities($(this).html()).replace($(this).text(), n));
return $(this);
}
Usage example
$('selector').textOnly('some text')
This is an improvement I've made to the jquery.uniform library.
Specifically the $.uniform.update()
function.
I took the idea from acheong87 and changed it a bit.
The idea is to change the text in a span but preserve the inner HTML and event bindings. No need to store and append HTML this way.
if ($e.is("input[type=button]")) {
spanTag = $e.closest("span");
var contents = spanTag.contents();
if (contents.length) {
var text = contents.get(0);
// Modern browsers support Node.TEXT_NODE, IE7 only supports 3
if (text.nodeType == 3)
text.nodeValue = $e.val();
}
}
Since you can't modify the link an option would be to simply use replace
$("a").html($("a").html().replace("Some text", "Other text"));
Example on jsfiddle.