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
$.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
});
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With