In this article, we’re going to create a mini search engine like Google or bing using just plain JavaScript. We’ll search for all the occurrences of a word or string in our web page. first we’ll create a html article to perform this search.

Make our search bar work with html.

<html>
<head>
<title>page search </title>
</head>
<body>
<input id='searchbar' onkeyup='search()'>
<p>
Welcome to Charming desk blog. Here we give tutorials on how to build your favorite web applications. We also give free source-codes of these web apps for your school projects.

</p>
<p>
The aim of starting this blog is to create a guide young web developers with alot of projects to practice on to enhance their skills and also build better projects.
</p>
<p>
Here at charming desk, we also sell fully developed e-commerce stores with an admin dashboard and also search engine friendly to help our clients boost their sales with google and also monitor their store's progress.
</p>
</body></html>





Now we’ve built our html page. We’re not going to add CSS to this article for more simplicity but I’m going to explain the scripts which is the main scope of this tutorial. We’re going to search for all the occurrences of the word written the search input in the above HTML and will display only paragraphs that containing that word.

/the JavaScript.

function search (){

//Select the search value.


var str= document.getElementById('search'). value;


//Select all the paragraphs.

var p= document.getElementsByTagName('p');

//loop through all paragraphs.

for(var i=0; i<p.length; i++){


//selects the paragraph texts.


var text= p[i].innerTEXT;

//show or hide paragraphs containing the word in the input.

if(text.indexOf(str)>-1){

p[i].style.display="block";

}

else{

p[i].style.display="none";

}
}

}


the "indexOf" method searches for the first occurrence of a given word and returns the position of the word either in an array or a string.

so in the above function, we searched for the value of the input in the code and if it is found i.e indexOf(str) > -1. Since a string starts counting from 0, the script will set it's paragraph display to be block, else it's paragraph's display will be set to null.

That's all there is to creating your own search bar to work. Feel free to leave us a feed back in the comments section or email us at hello@charmingdesk.com.ng for a private reply.

You can also follow us on social media here.

Kudos on your web development journey!

Categories: JavaScript

vic okeke

I'm just a web developer hoping to help out junior developers in algorithms for their projects.

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *