4

让我们有这样的html代码:

<div id="d1"><span>1.</span>Hallo <span>Kitty, </span><div>How are you?</div></div>

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

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

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

4

3 回答 3

6

这对你有用

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

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

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

演示

于 2012-10-10T13:05:00.650 回答
5

http://jsfiddle.net/SGZW4/

var text = $("#d1").contents().filter( function() {
    return this.nodeType === 3;
}).text();
于 2012-10-10T13:06:05.767 回答
2

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

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

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

于 2012-10-10T13:09:43.620 回答