如何获取元素后的文本节点?

使用jQuery。 我有以下html:

 All the world 

我怎么才能获得文本。 我应该使用什么选择器? (我需要“全世界”)

我也无法触摸HTML …

尝试使用DOM函数.nextSibling来选择下一个节点(包括文本节点)并使用nodeValue来获取文本All the world

 $(':checkbox')[0].nextSibling.nodeValue 

只需使用plain-JavaScript nextSibling ,尽管你必须“退出”jQuery才能使用该方法(因此[0] ):

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

JS小提琴演示 。

我终于意识到我的其他建议有什么问题,这个建议已经修复:

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

JS小提琴演示 。

并确保你只是从br 之前获取textNodes (虽然坦率地说这变得过于复杂,并且第一个建议更容易工作,我怀疑是可靠的):

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

JS小提琴演示 。

如果您在标记中添加了label (建议使用),您可以这样做:

HTML

  

JS

 var text = $( '#something ~ label:first' ).text();