Search code examples
javascriptjqueryxpathsizzle

jQuery/Sizzle to select Text nodes only (or, how to transform XPath expression to Sizzle)


I have the following XPath expression to get all textNodes within a element.

var textnodes = document.evaluate('descendant::text()', element, null, XPathResult.ORDERED_NODE_ITERATOR_TYPE, null);

Which works flawlessly across Chrome and Firefox, but IE.

Since Sizzle is browser-proof, I wanted to know, is there a way to select textNodes only with Sizzle/jQuery? As we all know, IE is a big deal, and there is no XPath for IE9 too (what about 10th?).

Or, in other words, how would I transform my XPath expression to Sizzle?


Solution

  • In jQuery, you can use filter and nodeType to get the text nodes in an element using:

    var textnodes = $('*').contents().filter(function(){
        return this.nodeType === 3;
    });