Find text between two tags/nodes

后端 未结 6 1169
北荒
北荒 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:49

    Well, you can try this...

    At least it works perfect when using 2 spans to merge them like your example (when an "empty" element is present). Otherwise, you will need to think a little to handle the span that lasts.

    (To check what I am talking about just take a look commenting the last line: nextElem.remove() and check the new div html).

    Live Demo: http://jsfiddle.net/oscarj24/t45MR/


    HTML:

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed massa.

    jQuery:

    $(document).ready(function () {
    
        var elem = $('#test');
    
        elem.contents().filter(function(index) {
            //Get index of an empty element
            if($.trim($(this).text()) === '') 
                //Merge the previous index span with the next index span texts
                mergeSpan(index);
        });
    
        //Print new inner html
        alert(elem.html());
    });
    
    function mergeSpan(index){
    
        //Get all 'div' elements
        var elems = $('#test').contents();
    
        //Get previous and next element according to index
        var prevElem = elems.eq(index - 1);
        var nextElem = elems.eq(index + 1);
    
        //Concat both texts
        var concatText = prevElem.text() + ' ' + nextElem.text();
    
        //Set the new text in the first span
        prevElem.text(concatText);
        //Remove other span that lasts
        nextElem.remove();
    };
    

    Result:

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed massa.

提交回复
热议问题