Skip to content

Instantly share code, notes, and snippets.

@WyrdNexus
Created August 17, 2017 23:52
Show Gist options
  • Save WyrdNexus/d07abcd20b3d020f6454727c693c8aa9 to your computer and use it in GitHub Desktop.
Save WyrdNexus/d07abcd20b3d020f6454727c693c8aa9 to your computer and use it in GitHub Desktop.
jQuery contents character count (all children)
$.fn.extend({
allText: function(){
var allTextResult;
this.each(function(){
result = $(this).find(":not(iframe)").addBack().contents().filter(function() {
return this.nodeType == 3;
});
if (typeof allTextResult === 'undefined' || allTextResult === null) {
allTextResult = result;
} else {
allTextResult.merge(result);
}
});
return allTextResult;
},
charCount: function (){
var total = 0;
this.each(function(){
$(this).allText().each(function(){
total += $(this).text().trim().length
});
});
return total;
}
});
$('div').charCount();
// total count of characters of all (white-space trimmed) text nodes of all matches
$('div').allText();
// collection of all text nodes of all children of all matches
/******* DANGER !!! **********
This method can be extreemly resource intensive, and double-counts nodes, if you are not careful with your selector!!
<div>
abc
<div>
ef
<div> G </div>
</div>
</div>
in the 'div' selector example above, the resulting count would be:
6 // for the first div
3 // for the second
1 // for the third
10 // total
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment