Javascript – Removing the text before an element with jQuery

domjavascriptjquery

Imagine this scenario:

<span>Item 1</span> | <span>Item 2</span>

How can I target the | and remove it? Also, assume I always need to remove the | before the span with "Item 2" in it, and the list can grow with items being added before OR after "Item 2." All new items will be enclosed within span and they'll be separated by |.

Best Answer

$('span').each(function() {
    if ($(this).text() == 'Item 2') {
        $(this.previousSibling).remove();
    }
});

http://jsfiddle.net/spFUG/2/