Drejc Drejc - 4 months ago 57
jQuery Question

JQuery change inner text but preserve html

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>

My current solution is following:

var aElem = $('a');
var children = aElem.children();

aElem.text("NEW TEXT");

But there must be some more elegant way of doing this.


This seems to work just fine.

Live Demo

        <a href="link.html">Some text <img src="img.jpg" /></a>

    <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.0/jquery.min.js"></script>
    <script type="text/javascript">
            var $link = $('a');
            var $img = $link.find('img'); 
            $link.html('New Text');