Find text between two tags/nodes

后端 未结 6 1146
北荒
北荒 2021-02-20 00:32

I thought that this would be rather straightforward, but I think the keywords are just too general so I keep getting query results for things like this and this.

Basical

6条回答
  •  [愿得一人]
    2021-02-20 00:44

    Heh . . . looks like Oscar Jara and I came up with similar ideas around using the JQuery .contents() method, but ended up with some considerably different implementations:

    $(document).ready(function () {
        $("#testDiv").contents().each(function() {
            var prevNode = this.previousSibling;
            var fillerText = "";
            while ((prevNode) && ($.trim($(prevNode).text()) === "")) {
                fillerText += prevNode.nodeValue;
                prevNode = prevNode.previousSibling;
            }
    
            if ((prevNode) && (this.nodeType === 1) && (prevNode.nodeType === 1)) {
                $(prevNode).text($(prevNode).text() + fillerText + $(this).text());
                $(this).remove();
            }
        });
    });
    

    I tested a few different sets of HTML data (three spans back-to-back, spans with spaces in between and without, etc.) all based on your original code, and it seems to work . . . the key was to skip over any "whitespace only" text nodes in between the tags, while preserving any needed spacing that they may have contained.

提交回复
热议问题