Join siblings with same class

by ryanwheale

HTML

<p>In the example below, any two neigboring elements with the same class will be joined into one so that:</p>
<pre><code>
    &lt;span class="highlighted"&gt;Here is&lt;/span&gt;
    &lt;span class="highlighted"&gt;some text.&lt;/span&gt;
</code></pre>
<p>...will become:</p>
<pre><code>
    &lt;span class="highlighted"&gt;Here is some text.&lt;/span&gt;
</code></pre>

<h3>Example</h3>
<h4>before:</h4>
<div>
Lorem <span class="highlighted">ipsum</span> dolor sit amet, <span class="highlighted">consectetur</span> <span class="highlighted">adipiscing</span> elit. Sed massa. Lorem <span class="highlighted">ipsum</span> dolor sit amet, <span class="highlighted">consectetur</span> <span class="highlighted">adipiscing</span> elit. Sed massa.
<div>
<h4>after:</h4>
<div id="test">
Lorem <span class="highlighted">ipsum</span> dolor sit amet, <span class="highlighted">consectetur</span> <span class="highlighted">adipiscing</span> elit. Sed massa. Lorem <span class="highlighted">ipsum</span> dolor sit amet, <span class="highlighted">consectetur</span> <span class="highlighted">adipiscing</span> elit. Sed massa.
<div>

CSS

.highlighted {
    border: 1px solid orange;
    background-color: yellow;
}

JavaScript

function joinNeighborsByClassName( className, scope ) {
    var items = (scope || 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', document.getElementById("test"));