2014-01-19 50 views
1

我想抓住所有包含文本的元素。jQuery:獲取所有包含文本的元素,因爲它是直接的子元素,包括後代?

$(*).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

嘗試

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

演示:Fiddle

相關問題