Stack overflow - delete

by Gerald Gillespie

HTML

<span class="authors">
    <a href="/url_one">Author One Name</a><span> - <a href="http://wsj.com">Wall Street Journal</a></span>, <a href="/url_one">Author Two Name</a><span> - <a href="http://wsj.com">Wall Street Journal</a></span>, and <a href="/url_one">Author Three Name</a><span> - <a href="http://wsj.com">Wall Street Journal</a></span>
</span>

JavaScript

var prevPub, // keep track of the previous publication
$a = $('.authors').find('a');

/* iterate through text nodes and remove them
http://stackoverflow.com/questions/9452340/iterating-through-each-text-element-in-a-page

then...
*/

$a.each(function (i) {
    var $this = $(this),
        delimiter = ', ',
        $prevAuthor = $a.eq(i - 3).length > 0 ? $a.eq(i - 3) : false,
        $thisAuthor = $a.eq(i - 1).length > 0 ? $a.eq(i-1) : false;

    console.log($this.text(),'\nprevAuthor: ',$prevAuthor.text(),
                '\nthisauthor: ',$thisAuthor, prevPub,'i: ',i);
    // look at the odd a elements
    if (i % 2 == 0 && i > 0) {
        console.log('continuing');
        return true;
    }

    if (prevPub == $this.text() && $prevAuthor) {
        // remove publication and redundant markup        
        $this.closest('span').remove();

        $prevAuthor.after($thisAuthor) // move author
        .after(delimiter); // add delimiter
    }
    prevPub = $this.text();
});