re1man
re1man

Reputation: 2367

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

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 could select only the text of ONLY the selected element, not its descendants.

Upvotes: 1

Views: 189

Answers (2)

dfreeman
dfreeman

Reputation: 2834

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)

Upvotes: 0

Jose Adrian
Jose Adrian

Reputation: 1247

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();

...

Upvotes: 2

Related Questions