How to get text node after element?

后端 未结 4 1003
太阳男子
太阳男子 2020-11-29 09:23

Using jQuery. I have the following html:

 All the world 

How w

4条回答
  •  爱一瞬间的悲伤
    2020-11-29 09:25

    Just use the plain-JavaScript nextSibling, though you have to 'drop out of' jQuery to use that method (hence the [0]):

    var text = $('input:checkbox[name="something"]')[0].nextSibling.nodeValue;
    

    JS Fiddle demo.

    And I finally realised what was wrong with my other suggestion, which has been fixed:

    var text = $('input:checkbox[name="something"]').parent().contents().filter(
        function(){
            return this.nodeType === 3 && this.nodeValue.trim() !== '';
        }).first().text();
    

    JS Fiddle demo.

    And to make sure that you're only getting the textNodes from before the br (though frankly this is becoming overly-complex, and the first suggestion works far more easily and, I suspect reliably):

    var text = $('input:checkbox[name="something"]').parent().contents().filter(
        function(){
            return this.nodeType === 3 && this.nodeValue.trim() !== '' && $(this).prevAll('br').length === 0;
        }).text();
    

    JS Fiddle demo.

提交回复
热议问题