Javascript

Buy me a beer or a book?

amazon PayPal - The safer, easier way to donate online!

Search HTML page content using Javascript

I was helping a friend on a forum recently, and found quite a nifty tool to help him have a huge downloadable page, and keep the search functionality, and it was by using Javascript to make a Search function loop through the HTML elements within the page and detect the search results and highlight them using CSS. Anyway enough blabber, here is the code:

The Javascript/HTML shows you what you need to put in place for the HTML form when posting (note this is NOT HTML strict valid - only Transitional).

HTML and Javascript search form
1
2
3
4
5
6
<form>
<input type="text" size="200" style="padding:2px;" id="text" />
<a href="#" onclick="javascript:void($('body').removeHighlight().
highlight(document.getElementById('text').value)); return false;">
Search</a>
</form>

Here is the CSS I used to highlight the text found by the Javascript Search functions.
1
2
3
<style type="text/css">
.highlight { background-color: yellow }
</style>

Also here are the links to the two Javascript files you will need for the above to work.

You will need jQuery, and a file using the jQuery library jquery.highlight.js
  • Anonymous

    Posted at 2010-06-30 00:32:49

    umm, demo?

    Reply to comment

  • Anonymous

    Posted at 2010-02-15 16:05:10

    How comes it doesn't search the page when i click the search word :sad:

    Reply to comment

  • Anonymous

    Posted at 2009-07-12 19:41:08

    My Firefox 3.5 hangs up when I click on the highlighter link with an empty highlighter text box.

    I think a conditional statement should be placed in the code, that will fix the issue.

    javascript:if (document.getElementById(\'text\').value.length > 0) { void($(\'body\').removeHighlight().highlight(document.getElementById(\'text\').value)); } return false;

    Great code snippet anyways, thank you!

    Reply to comment

    • Anonymous

      Posted at 2009-07-12 21:15:45

      Yeah, there seems to be an issue with that, thanks for the feedback though!

      Reply to comment

Post your comments...

Free Downloads