0

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?

tomsseisums
  • 13,168
  • 19
  • 83
  • 145

2 Answers2

0

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;
});
Joseph
  • 117,725
  • 30
  • 181
  • 234
  • The result set doesn't match. `.contents().filter()` appears to be selecting only direct children of `element`, where XPath's `descendant::text()` looks recursively at all childs of `element`. P.S. Is http://api.jquery.com/ working for you? Appears to be down for me. – tomsseisums May 05 '12 at 23:42
  • 1
    this should probably be `$(element).find('*').andSelf().contents()` etc – georg May 05 '12 at 23:44
  • 1
    @thg435 nails it! At edited of @Joseph, that one loses the `element` context now. – tomsseisums May 05 '12 at 23:59
  • 1
    @thg435 you should post that as an answer – Joseph May 06 '12 at 00:12
0

Try my solution from here. It even allows you to filter the text nodes themselves without extra functions, as well as use .end().

Community
  • 1
  • 1