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

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

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

**text to change** text t
14条回答
  •  半阙折子戏
    2020-11-22 08:09

    Lots of great answers here but they only handle one text node with children. In my case I needed to operate on all text nodes and ignore html children BUT PRESERVE THE ORDERING.

    So if we have a case like this:

    Some text
    Child1
    Child2
    and some other text
    Child3
    Child4
    and here we are again

    We can use the following code to modify the text only AND PRESERVE THE ORDERING

        $('#parent').contents().filter(function() {
            return this.nodeType == Node.TEXT_NODE && this.nodeValue.trim() != '';
        }).each(function() {
        		//You can ignore the span class info I added for my particular application.
            $(this).replaceWith(this.nodeValue.replace(/(\w+)/g,"$1X"));
    	});
    
    
    Some text
    Child1
    Child2
    and some other text
    Child3
    Child4
    and here we are again

    Here is the jsfiddle of it working

提交回复
热议问题