How To Select Own Text Of The Element Using Jquery
I have the following html:  
Text1
         Text2          
- Tex
 
Solution 1:
$.fn.ownText = function() {
    returnthis.eq(0).contents().filter(function() {
       returnthis.nodeType === 3// && $.trim(this.nodeValue).length;
    }).map(function() {
       returnthis.nodeValue;
    }).get().join('');
}
var text = $('#t2').ownText();
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
});
Solution 2:
Try
functiongetText(el) {
    return $(el).contents().map(function () {
        returnthis.nodeType == 3 && $.trim(this.nodeValue) ? $.trim(this.nodeValue) : undefined;
    }).get().join('')
}
$('div *').each(function () {
    console.log(this.id, getText(this))
})
Demo: Fiddle
Solution 3:
Better way to do it is :
    $("selector").clone().children().remove().end().text(); 
Demo here :
This is not optimized version but you can optimize it :-) Thank you!
Solution 4:
try this
var n = newArray();
 $("div div, li").each(function () {
    n[$(this).attr('id')] = $(this).text()
 })
 console.log(n)
Post a Comment for "How To Select Own Text Of The Element Using Jquery"