1

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.

user2526777
  • 75
  • 1
  • 6

1 Answers1

1
$.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);
    }
});
Daniel
  • 579
  • 2
  • 7
  • this seems to be case sensitive, any way to change that? – user2526777 Aug 13 '13 at 02:15
  • Updated with a case insensitive search option. This option caches all text content into a variable. This reduces the overhead on additional searches. – Daniel Aug 13 '13 at 15:43