jQuery:获取文本的所有元素';s的直系子女,包括后代?
我想抓取所有包含文本的元素jQuery:获取文本的所有元素';s的直系子女,包括后代?,jquery,dom,Jquery,Dom,我想抓取所有包含文本的元素 $(*).each(function(){ if ($(this).nodeType == 3) return $(this).parent(); }).get(); 但是如果有一个元素 <div>somewhere <span class='special'> here <b>now</b></span></div> 现在就在这里的某个地方 但是,使用我的代码,它将分别返回某处和此
$(*).each(function(){
if ($(this).nodeType == 3) return $(this).parent();
}).get();
但是如果有一个元素
<div>somewhere <span class='special'> here <b>now</b></span></div>
现在就在这里的某个地方
但是,使用我的代码,它将分别返回某处
和此处
和现在
。我想让它现在返回这里的某个地方
如果一个元素只有文本内容,那么就可以了
<div>only this</div>
只有这个
应该只给我这个,因为它没有后代
我担心的是大型集装箱会被退回,比如:
<div>
<a>some</a>
<b>where</b>
</div>
一些
哪里
这应该会给我一些和where,而不是整个
div`因为中间有很多空格。试试看
function get(ct) {
return $(ct).find('*').filter(function () {
return $(this).contents().filter(function () {
return this.nodeType == 3 && $.trim(this.nodeValue) != '';
}).length != 0
});
}
演示: