Replace word in

in

using jquery

前端 未结 8 1799
无人及你
无人及你 2021-01-18 11:54

I have a document with the following structure:

This is some text.

8条回答
  •  离开以前
    2021-01-18 12:30

    This is an overkill but anyway:

    function replaceNodeText() {
        if (this.nodeType === 3) {
            this.nodeValue = this.nodeValue.replace(replaceNodeText.find, replaceNodeText.replace);
        } else {
            $(this).contents().each(replaceNodeText);
        }
    }
    replaceNodeText.find = "some";
    replaceNodeText.replace = "my";
    $("#notice").contents().each(replaceNodeText);
    

    This function will preserve any html present inside the specified element. For example it will work on this HTML:

    This is
    some text.

    This is so
    me text.

    This is some text.

    And produce the following output:

    This is
    my text.

    This is so
    me text.

    This is my text.

    Demo here

提交回复
热议问题