I am new to JavaScript. Trying to create a small user interface that searches for a list of words when we run a query in the search field. At the same time, I want to highlight the corresponding substring of each word in the list so that the user can immediately see how the word matches the query. To achieve this, I included the highlight function in my code, referring to some basic JS tutorials. But due to some kind of error, it does not work. Could you help me. Thank..!!!
function getFullName(item,index) {
return "<li>"+item.firstname + "<span class='tool-tip'>" +item.lastname+"</span> "+ item.id+"</li>";
}
function myFunction1() {
document.getElementById("demo").innerHTML = persons.map(getFullName);
}
function myFunction() {
var input, filter, ul, li, a, i,count=0;
input = document.getElementById("myInput");
filter = input.value.toUpperCase();
var longWords = persons.filter(function(person){
return person.firstname.toUpperCase().indexOf(filter) > -1
});
var message = "Result:" + longWords.length + " words containing '" + input.value;
document.getElementById("demo").innerHTML=message;
ul = document.getElementById("myUL");
ul.innerHTML= longWords.map(getFullName);
highlight();
}
function highlight(){
var inputText, filter1,innerHTML,index;
inputText = document.getElementById("myInput");
console.log(inputText);
filter1 = inputText.value.toUpperCase();
console.log(filter1);
innerHTML1 = inputText.innerHTML;
console.log(innerHTML1);
index1 = innerHTML1.indexOf(filter1);
if ( index1 >= 0 )
{
innerHTML1 = innerHTML1.substring(0,index1) + "<span class='highlight'>" + innerHTML1.substring(index1,index1+filter1.length) + "</span>" + innerHTML1.substring(index1 + filter1.length);
filter1.innerHTML = innerHTML1;
}
}
here is the CSS file:
.highlight{
font-weight:bold;
color:black;
}
source
share