jQuery, selecting the text of a li minus

Hi I currently have a script that extracts the text from an li using:

$(‘li’).text();

simply enough.

But I have span within the li, and the text within the span is also being selected. Is there a way to remove the span text from the selection?

Try this…


$('li').clone().children().remove().text()

that seems to have the opposite effect of retaining the span text but removing the li text?

Sorry missed a piece there…


$('li').clone().children().remove().end().text();

Eh, semantic7’s solution is nice, but a bit much for something so simple.

Here’s a plugin that’ll handle it:


jQuery.fn.directText = function() {
    
    var node = this[0].firstChild, txt = '';
    
    if (node) do {
        if (node.nodeType === 3) {
            txt += node.data;
        }
    } while (node = node.nextSibling);
    
    return txt;
    
};

Usage:


jQuery('li').directText();

This’ll be A LOT faster than clone()'ing, remove()'ing children etc. etc.