JQuery change inner text but preserve html

前端 未结 14 2755
名媛妹妹
名媛妹妹 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: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')

提交回复
热议问题