How can I change an element's text without changing its child elements?

前端 未结 14 2342
难免孤独
难免孤独 2020-11-22 07:30

I\'d like to update element\'s text dynamically:

**text to change** text t
14条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 08:07

    Problem with Mark's answer is that you get empty textnodes aswell. Solution as jQuery plugin:

    $.fn.textnodes = function () {
        return this.contents().filter(function (i,n) {
            return n.nodeType == 3 && n.textContent.trim() !== "";
        });
    };
    
    $("div").textnodes()[0] = "changed text";
    

提交回复
热议问题