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.
All HTML elements have inner HTML properties. The . html() jQuery method retrieves the HTML content of the first element in the particular set of matched elements. Remember: jQuery innerHTML does not exist as a function.
To set the value of innerHTML property, you use this syntax: element. innerHTML = newHTML; The setting will replace the existing content of an element with the new content.
If you want to return or change just the text inside an element, use innerText. If you want to return or change just the text inside hidden elements, use textContent.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With