开发者

get the text of only the selected element not its descendants in jquery

开发者 https://www.devze.com 2023-03-26 21:21 出处:网络
I have this code : $(\'p:not(:has(iframe))\').filter(function(){ return $(this).text().length > 150;})

I have this code :

$('p:not(:has(iframe))').filter(function(){
    return $(this).text().length > 150;})
    .slice(0,1).parent();

According to the docs, .text gets the text of the descendants also, and I was wondering how I coul开发者_开发知识库d select only the text of ONLY the selected element, not its descendants.


This is nos the best way but... i think it would work.

$('p:not(:has(iframe))').filter(function(){
    var _cp = $(this).clone();
    var tiw = _cp.children().remove().end().text();

    return tiw.length > 150;
}).slice(0,1).parent();

...


Does this fit your need?

$('p:not(:has(iframe))').filter(function(){
    var total_length = 0;
    for (var i=0; i<this.childNodes.length; ++i)
        if (this.childNodes[i] instanceof Text)
            total_length += this.childNodes[i].length;

    return total_length > 150;
}).slice(0,1).parent();

(This avoids the need to clone each node as you are traversing the DOM)

0

精彩评论

暂无评论...
验证码 换一张
取 消