3

I have a one page website that I am trying to add a search feature to. Using pure javascript (no jquery) I want to take whatever word/phrase is entered in the search box, and search the content/HTML of different li's. I'm guessing I'll have to use some combination of innerHTML and .indexOf, but I'm not sure. Here is a link to the site I am referring to http://www.executiveinsurance.com/ Any help would be much appreciated!!!

2 Answers2

1

You could do something like this

var searchKeyword = "sampleSearch";   
var allLis = document.getElementsByTagName("li");
var searchResults = [];
for(var i=0;i<allLis.length;i++){
if(allLis[i].innerHtml.indexOf(searchKeyword)>-1){
searchResults.push(allLis[i]);
}

The searchResults array should contain the elements that have the searchKeyword in them. I haven't tested this but you get the idea.

ama2
  • 2,611
  • 3
  • 20
  • 28
1

Just to start with, you can build on this

function search()
{
    var lis = document.getElementsByTagName("li");
    var searchText = document.getElementById("searchBox").value;

    for(var i=0;i<lis.length;i++)
    {
        if(lis[i].innerHTML.indexOf(searchText) > -1)
           lis[i].style.color = 'red';
    }
}​

Just if you care to highlight the specific words

lis[i].innerHTML = lis[i].innerHTML.replace(searchText,'<span style="color:red">'+searchText+'</span>');

SEE JsFiddle DEMO HERE

codingbiz
  • 26,179
  • 8
  • 59
  • 96