JQuery change inner text but preserve html

前端 未结 14 2689
名媛妹妹
名媛妹妹 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:47

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

    An efficient and robust way that doesn't require you to know what the inner elements are or what the text is:

    var $a = $('a');
    var inner = '';
    $a.children.html().each(function() {
        inner = inner + this.outerHTML;
    });
    $a.html('New text' + inner);
    
    0 讨论(0)
  • 2020-12-01 07:48

    You can change it by .contents()

    $('.yourElement').contents()[0].data = 'New Data';
    

    where in your case the "[0].data" is your text data

    0 讨论(0)
  • 2020-12-01 07:50

    I added a jQuery function for that need.

    you may need to convert the html-entities to text representation, so i added decodeEntities function.

    function decodeEntities(encodedString) {
     if (typeof encodedString != "string") return encodedString;
     if (!encodedString) return "";
     var textArea = document.createElement('textarea');
     textArea.innerHTML = encodedString;
     return textArea.value;
    }
    jQuery.fn.textOnly = function(n) {
      if (this.length > 0)
       $(this).html(decodeEntities($(this).html()).replace($(this).text(), n));
      return $(this);
     }
    

    Usage example $('selector').textOnly('some text')

    0 讨论(0)
  • 2020-12-01 07:52

    This is an improvement I've made to the jquery.uniform library. Specifically the $.uniform.update() function. I took the idea from acheong87 and changed it a bit.

    The idea is to change the text in a span but preserve the inner HTML and event bindings. No need to store and append HTML this way.

    if ($e.is("input[type=button]")) {
        spanTag = $e.closest("span");
        var contents = spanTag.contents();
    
        if (contents.length) {
            var text = contents.get(0);
    
            // Modern browsers support Node.TEXT_NODE, IE7 only supports 3
            if (text.nodeType == 3)
                text.nodeValue = $e.val();
        }
    }
    
    0 讨论(0)
  • 2020-12-01 07:54

    Since you can't modify the link an option would be to simply use replace

    $("a").html($("a").html().replace("Some text", "Other text"));
    

    Example on jsfiddle.

    0 讨论(0)
提交回复
热议问题