Created
August 17, 2017 23:52
-
-
Save WyrdNexus/d07abcd20b3d020f6454727c693c8aa9 to your computer and use it in GitHub Desktop.
jQuery contents character count (all children)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$.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; | |
} | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('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