JQuery change inner text but preserve html

前端 未结 14 2688
名媛妹妹
名媛妹妹 2020-12-01 06:56

I would like to change the text of a HTML element but preserve the rest of the inner html with jQuery.

For instance:

Some         


        
相关标签:
14条回答
  • 2020-12-01 07:37

    My generic version:

    let button = $('#yourElement');
    button.html(button.html().replace(button[0].innerText, "New Text"));
    
    0 讨论(0)
  • 2020-12-01 07:39

    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>
    
    0 讨论(0)
  • 2020-12-01 07:40

    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>
    
    0 讨论(0)
  • 2020-12-01 07:40

    try this code

    $('a').live('click', function(){
        var $img = $(this).find('img'); 
        $(this).text('changed');
        $(this).append($img);
    });
    
    0 讨论(0)
  • 2020-12-01 07:41

    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:

    1. contents() includes text nodes, unlike children().
    2. It is necessary to create a copy of the contents via var contents = ... or else the remaining elements are lost forever once replaced by $(this).html('NEW TEXT').
    3. The length check is optional but recommended.
    4. The nodeType check is optional but recommended.
    0 讨论(0)
  • 2020-12-01 07:45

    Shorthand for more elements and leading text to change:

    elemshtml = '';
    $("a *").each(function(){elemshtml +=$(this)[0].outerHTML});
    $("a").html('Some text' + elemshtml);
    
    0 讨论(0)
提交回复
热议问题