Reputation: 91
I want to be able to count everything on a site that contains a certain string, even if it's not displayed on the page.
I found this:
window.occurrencesFunc()
I am not sure how to use it. I did play around with it, but nothing seemed to work.
This is what I tried:
function main() {
function(r) {
var amount = window.occurrencesFunc(r, "string", false);
$('ul.reset').append('Count: ' + amount);
}
}
main();
Upvotes: 2
Views: 3244
Reputation: 10849
I'd probably walk through element nodes present in the DOM
function countElementsMatching(needle, elements) {
return Array.prototype.slice.call(elements)
.map(function (node) {
return node.textContent;
})
.filter(function (str) {
return str.indexOf(needle) !== -1;
}).length;
}
Usage:
var total = countElementsMatching('some string', document.querySelectorAll('*'));
Upvotes: 0
Reputation: 1446
How about a function like this?
function findOccurrences (string)
{
var elements = document.getElementsByTagName ('*');
var foundCount = 0;
for (var i = 0, il = elements.length; i < il; i++) {
if (!elements[i].textContent || !elements[i].textContent.match (string)) {
continue;
}
foundCount++;
}
return 'Count: ' + foundCount;
}
Use it like this, HTML...
<div id="occurrenceCount"></div>
And the JavaScript...
var countElement = document.getElementById ('occurrenceCount');
countElement.textContent = findOccurrences ('your string');
This will make the <div>
above contain something like:
Count: 35
Upvotes: 0
Reputation: 1167
I'd get the entire page as a string:
var markup = document.documentElement.innerHTML;
And, then I'd use the match method to match for the string occurrences in the string and count them:
// the g in the regular expression says to search for a word (not part of a word)
var resultArray= markup.match(/WORRDDD/g);
var count = resultArray.length
Shorthand, would be
var count = (markup.match(/WORRDDD/g) || []).length;
Upvotes: 3