如何获取不属于子元素的容器内的文本

我们有这样的HTML代码:

1.Hallo Kitty,
How are you?

这只是一个例子,里面可能有不同的子元素。

如何获取不属于子元素的d1容器内的文本?

对于上面的例子,它只是"Hallo "

http://jsfiddle.net/SGZW4/

 var text = $("#d1").contents().filter( function() { return this.nodeType === 3; }).text(); 

这对你有用

 $('#d1') .contents() .filter(function() { return this.nodeType == Node.TEXT_NODE; }).text() 

或者您也可以使用下面建议的旧浏览器支持

 var text = $("#d1").contents().filter( function() { return this.nodeType === 3; }).text(); 

演示

改进halex的技巧,你可以利用.children .children()只找到DOM节点并忽略文本节点的事实:

 var text = $('#d1').clone().children().remove().end().text(); // string "Hallo " 

…但我更喜欢.nodeType技术,因为它更清楚你在做什么。