Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select own text of the element using jQuery

I have the following html:

<div>
    <div id="t1">Text1</div> 
    <div id="t2">
        Text2 
        <ul id="t3">
            <li id="t4">Text3</li>
        </ul>
    </div>
</div>

I want to select only own text for each element. I tried to use jQuery text function, but it returns the combined text content of all elements in selection:

t1 => Text1
t2 => Text2 Text3
t3 => Text3
t4 => Text3

And what I need:

t1 => Text1
t2 => Text2
t3 =>
t4 => Text3 
like image 483
alexmac Avatar asked Jan 21 '14 05:01

alexmac


2 Answers

$.fn.ownText = function() {
    return this.eq(0).contents().filter(function() {
       return this.nodeType === 3 // && $.trim(this.nodeValue).length;
    }).map(function() {
       return this.nodeValue;
    }).get().join('');
}

var text = $('#t2').ownText();

http://jsfiddle.net/5L9Ww/

A slightly faster alternative:

$.fn.ownText = function() {
    var children = this.get(0).childNodes, 
        l = children.length,
        a = [];
    for (var i = 0; i < l; i++) {
      if (children[i].nodeType === 3) 
          a.push(children[i].nodeValue);
    }
    return a.join('');
}

Or a different method that accepts a glue for joining the node's values and an option for trimming the result:

$.fn.ownText = function(o) {
    var opt = $.extend({ glue: "", trim: false }, o),
        children = this.get(0).childNodes, 
        l = children.length,
        a = [];
    for (var i = 0; i < l; i++) {
        if (children[i].nodeType === 3) {
          var val = children[i].nodeValue;
          a.push(opt.trim ? $.trim(val) : val);
        }
    }
    return a.join(opt.glue);
}

$('#t2').ownText({
    glue: ',',
    trim: true
});
like image 151
undefined Avatar answered Oct 24 '22 21:10

undefined


Try

function getText(el) {
    return $(el).contents().map(function () {
        return this.nodeType == 3 && $.trim(this.nodeValue) ? $.trim(this.nodeValue) : undefined;
    }).get().join('')
}

$('div *').each(function () {
    console.log(this.id, getText(this))
})

Demo: Fiddle

like image 43
Arun P Johny Avatar answered Oct 24 '22 21:10

Arun P Johny