Find text between two tags/nodes

后端 未结 6 1067
北荒
北荒 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-20 00:51

    I know you have already accepted a solution, but I wanted to take the challenge to provide a pure javascript solution which can be incorporated into your toolset. Here's what I came up with, and would like any help to make this better.

    http://jsfiddle.net/ryanwheale/JhZPK/

    function joinNeighborsByClassName( className ) {
        var items = document.getElementsByClassName(className),
            next = null,
            remove = [],
            append = '',
            i = 0;
    
        while( i < items.length && (next = items[i++]) ) {
            while( (next = next.nextSibling) && next !== null ) {
                if((next.nodeType === 3  && /^\s+$/.test(next.nodeValue)) ||     
                   (new RegExp("(?:^|\s)" + className + "(?!\S)", "g")).test(next.className) ) {
                    append += (next.innerHTML || next.nodeValue);
    
                    if(next.nodeType !== 3) {
                        remove.push(next);
                    }
                } else {
                    break;
                }
            }
    
            if(append) items[i-1].innerHTML += append;
            for(var n = 0; n < remove.length; n++) {
                remove[n].parentNode.removeChild(remove[n]);
            }
    
            remove = [];
            append = '';
        }
    }
    
    joinNeighborsByClassName('highlighted');
    

提交回复
热议问题