Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Simple Javascript/XML Based Search

DZone's Guide to

Simple Javascript/XML Based Search

·
Free Resource
// Use javascript to search an XML based index.
// Provides simple site search where no server-side
// alternatives are available (for example: on a CD ROM)

// The sample XML:


  

  
	
   
    John
   
	
   
    Paul
   
	
   
    George
   
	
   
    Ringo
   

  


// The javascript:

window.onload = loadIndex;

function loadIndex() { // load indexfile
// most current browsers support document.implementation
	if (document.implementation && document.implementation.createDocument) {
		xmlDoc = document.implementation.createDocument("", "", null);
		xmlDoc.load("index.xml");
	}
// MSIE uses ActiveX
	else if (window.ActiveXObject) {
		xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
		xmlDoc.async = "false";
		xmlDoc.load("index.xml");
	}
}


function searchIndex() { // search the index (duh!)
	if (!xmlDoc) {
		loadIndex();
	}
	// get the search term from a form field with id 'searchme'

	var searchterm = document.getElementById("searchme").value;
	var allitems = xmlDoc.getElementsByTagName("item");
	results = new Array;
	if (searchterm.length < 3) {
		alert("Enter at least three characters");
	} else {
		for (var i=0;i
  
    0) {
// if there are any results, put them in a list inside the "resultshere" div
		var resultshere = document.getElementById("resultshere");
		var header = document.createElement("h5");
		var list = document.createElement("ul");
		var searchedfor = document.createTextNode("You've searched for "+searchterm);
		resultshere.appendChild(header);
		header.appendChild(searchedfor);
		resultshere.appendChild(list);
		for (var i=0;i
   
    

// Here's some s(a|i)mple HTML that should work with the code above:


    






     
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}