最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Determine if element is a text node using jQuery - Stack Overflow

programmeradmin0浏览0评论

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!

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!

Share Improve this question edited Sep 29, 2011 at 13:47 Abs asked Sep 29, 2011 at 13:21 AbsAbs 57.9k103 gold badges281 silver badges416 bronze badges 2
  • 1 check this, may be, dont know: developer.mozilla.org/en/nodeType – Ricardo Binns Commented Sep 29, 2011 at 13:27
  • The accepted answer to this question can be useful too: stackoverflow.com/questions/298750/… – mamoo Commented Sep 29, 2011 at 13:30
Add a comment  | 

2 Answers 2

Reset to default 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);
    }
});

as the comment:

check this nodeType and see if helps you.

发布评论

评论列表(0)

  1. 暂无评论