I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.
For instance:
<a href="link.html">Some text <img src="image.jpg" /></a>
replace "Some text" with "Other text", and the result should look like:
<a href="link.html">Other text <img src="image.jpg" /></a>
EDIT: My current solution is following:
var aElem = $('a');
var children = aElem.children();
aElem.text("NEW TEXT");
aElem.append(children);
But there must be some more elegant way of doing this.
This seems to work just fine.
<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>
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' );