Reputation: 75
I'm trying to search an entire page for about 20+ individual words. If any of the words exist I want and alert to appear with the word that was found. I've got this far:
if ($("body").has(":contains('Stunning')").length) {
alert("Stunning");
}
But I need to specify multiple words and also have the alert display the specific word that was found.
Any help is appreciated.
Upvotes: 1
Views: 1357
Reputation: 579
$.each(['iste','quia','birds','words'],function(index, value){
var present = $("body:contains('"+value+"')").length;
if(present){
alert(value);
}
});
Here is a working Fiddle. http://jsfiddle.net/DNKdm/
EDIT: http://jsfiddle.net/k7aEV/2/
var searchText = getPageText(),
wordlist = ['Sed','Neque','birds','words'];
//Based on solution found at
//http://stackoverflow.com/questions/298750/how-do-i-select-text-nodes-with-jquery
function getTextNodesIn(node, includeWhitespaceNodes) {
var textNodes = [], whitespace = /^\s*$/;
function getTextNodes(node) {
if (node.nodeType == 3) {
if (includeWhitespaceNodes || !whitespace.test(node.nodeValue)) {
textNodes.push(node.nodeValue);
}
} else {
for (var i = 0, len = node.childNodes.length; i < len; ++i) {
getTextNodes(node.childNodes[i]);
}
}
}
getTextNodes(node);
return textNodes;
}
function getPageText (){
var el = document.getElementById('wrapper'), //Replace with body or content wrapper div.
pageTxt = getTextNodesIn(el).join(' ').replace(/[^\w ]/g," ").toLowerCase()+" ";
return pageTxt;
}
$.each(wordlist,function(index, value){
var found = searchText.indexOf(value.toLowerCase()+" "); //remove the space if you don't want whole words only.
if(found !== -1){
alert('Found: '+value);
}
});
Upvotes: 1