7

Given a jQuery element, how can I determine if the sibling on the right is a text node and not another element? In PHP, you would compare the nodeType to #text - what's the equivalent in this case?

window.jQuery('body').find('a').each(function (i) {


    if(window.jQuery(this).next() == '?'){

    }


});

I am trying to work out what I can put in the condition part.

Update

    if(window.jQuery(this).next().length != 0){

        alert(window.jQuery(this).next().get(0).nodeType);  

        if(window.jQuery(this).next().get(0).nodeType == 3){

            alert('right has text');

        }

For some reason, all my tests keep returning a 1 rather than a 3 to indicate text nodes!

Abs
  • 56,052
  • 101
  • 275
  • 409
  • 1
    check this, may be, dont know: https://developer.mozilla.org/en/nodeType – Ricardo Binns Sep 29 '11 at 13:27
  • The accepted answer to this question can be useful too: http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery – mamoo Sep 29 '11 at 13:30

2 Answers2

18

next() only returns elements, so you can't use it to traverse text nodes. You could instead use the DOM nextSibling property and check its nodeType property:

Live demo: http://jsfiddle.net/kD9qs/

Code:

window.jQuery('body').find('a').each(function (i) {
    var nextNode = this.nextSibling;
    if (nextNode && nextNode.nodeType == 3) {
        alert("Next sibling is a text node with text " + nextNode.data);
    }
});
Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • beat me while i was writing exactly the same +1. it took me longer because i was reading jQuery source – Einacio Sep 29 '11 at 13:59
2

as the comment:

check this nodeType and see if helps you.

Ricardo Binns
  • 3,228
  • 6
  • 44
  • 71
  • Thanks for this, but nodes keep returning as 1 rather than 3 to indicate a text node! I have updated question with what I have so far. – Abs Sep 29 '11 at 13:47