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!!!
Asked
Active
Viewed 202 times
3
-
1This is what you need http://stackoverflow.com/questions/12505602/slow-highlighting-in-firefox/12505656#12505656 – elclanrs Oct 10 '12 at 02:46
-
@elclanrs the accepted answer hangs google chrome browser – codingbiz Oct 10 '12 at 03:00
-
My answer works fine AFAIK... – elclanrs Oct 10 '12 at 03:02
-
Yes, yours worked - great stuff – codingbiz Oct 10 '12 at 03:04
2 Answers
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>');

codingbiz
- 26,179
- 8
- 59
- 96
-
You can also check @elclanrs answer in the posted links in the comment. – codingbiz Oct 10 '12 at 03:06