I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.
For instance:
Some
My generic version:
let button = $('#yourElement');
button.html(button.html().replace(button[0].innerText, "New Text"));
You'll need to add in a <span>
element and change the text of that element, e.g.:
<a href="link.html"><span id="foo">Some text</span><img src="image.jpg" /></a>
Then, you can call from jQuery:
$("#foo").html("Other text");
And your result will effectively be:
<a href="link.html"><span id="foo">Other text</span><img src="image.jpg" /></a>
This seems to work just fine.
Live Demo
<html>
<head>
</head>
<body>
<a href="link.html">Some text <img src="img.jpg" /></a>
</body>
</html>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
var $link = $('a');
var $img = $link.find('img');
$link.html('New Text');
$link.append($img);
});
</script>
try this code
$('a').live('click', function(){
var $img = $(this).find('img');
$(this).text('changed');
$(this).append($img);
});
My solution, though a little late.
$('a').each(function() {
var contents = $(this).contents();
if (contents.length > 0) {
if (contents.get(0).nodeType == Node.TEXT_NODE) {
$(this).html('NEW TEXT').append(contents.slice(1));
}
}
});
Some notes:
contents()
includes text nodes, unlike children()
.var contents = ...
or else the remaining elements are lost forever once replaced by $(this).html('NEW TEXT')
.length
check is optional but recommended.nodeType
check is optional but recommended.Shorthand for more elements and leading text to change:
elemshtml = '';
$("a *").each(function(){elemshtml +=$(this)[0].outerHTML});
$("a").html('Some text' + elemshtml);