jQuery:获取带有文本的所有元素,因为它是直接的孩子,包括后代?

时间:2014-01-19 04:25:16

标签: jquery dom

我想抓住包含文字的所有元素。

$(*).each(function(){
    if ($(this).nodeType == 3) return $(this).parent();
}).get();

然而,当有像

这样的元素时
<div>somewhere <span class='special'> here <b>now</b></span></div>

但是,使用我的代码,它将分别返回<div>somewhere </div><span>here</span>以及<b>now</b>。我希望它能够返回<div>somewhere here now</div>

如果元素只有文本内容,那么这很好

<div>only this</div>

应该给我<div>only this</div>,因为它没有后代。

我担心的是大容器返回如下:

<div>

<a>some</a>

<b>where</b>

</div>

应该给我<a>some</a><b>where</b>, and not the whole div`,因为它们之间有很多空格。

1 个答案:

答案 0 :(得分:1)

尝试

function get(ct) {
    return $(ct).find('*').filter(function () {
        return $(this).contents().filter(function () {
            return this.nodeType == 3 && $.trim(this.nodeValue) != '';
        }).length != 0
    });
}

演示:Fiddle

相关问题