Search code examples
javascripthtmlcsshighlighting

How to change color for mismatch words in HTML using javascript


I have a span and an input field; I want to change the color of the text in span when I enter that text in input field.

Following is my code:

i want, if i type wrong word then that word will red in span

var i=0;
var idx=0;
document.body.onkeydown = function(e){

    if(e.keyCode == 32 )
    
{
highlight();
}
}
function highlight() {
  var str= document.getElementById("pera").innerText.split(' ');
  var text= str[i];
  var wrdl = text.length;
  var inputText = document.getElementById("pera");
  var innerHTML = inputText.innerText;
	var pretext = innerHTML.slice(0, idx);
	var postext = innerHTML.slice(idx+text.length);
	
  if ( idx >= 0 && text!="")
    {      
var highlightedText = pretext;	
	  highlightedText += "<span class='highlight'>";
		highlightedText += text;
		highlightedText += "</span>";
		highlightedText += postext;
		 		document.getElementById("pera").innerHTML=highlightedText;
    }
	
i++;
idx += parseInt(text.length+1);
}
.highlight
{
background-color:yellow;

}
<span id="pera">This paragraph is a value of span</span>
</br>
<input type="text" id ="inp" onfocus="highlight();" />


Solution

  • This code should highlight in green the parts that match, and in red the parts that do not.

    It works by finding the index of the first occurrence of the text that the user entered, and adding the starting and ending <span> tags around it.

    function highlight() {
    
      const text = "This paragraph is a value of span"; //The actual text to compair the value against
    
      var value = document.getElementById("in").value; //The input value
    
      var startingIndex = text.indexOf(value); //The string index where the value begins in the paragraph
      
      if (startingIndex!=-1) { //If the value is within the text
      
        var endingIndex = startingIndex+value.length; //The string index where the value ends is just the length of the value added to the starting index
      
        var highlightedText = text.slice(0,startingIndex); //The text from the beginning to the start of the highlight
        highlightedText += "<span style=\"color:green;\">"; //Add the HTML which will cause the highlight
        highlightedText += text.slice(startingIndex,endingIndex); //Add the text to highlight
        highlightedText += "</span>"; //Add the HTML which will cause the end of the highlight
        highlightedText += text.slice(endingIndex); //Add the remaining text
        
        document.getElementById("para").innerHTML = highlightedText; //Set the HTML of the paragraph to be the new, highlighted string that we made.
        
      }
      
    }
    <span id="para" style="color:red"><span style="color:green">This paragraph is</span> a value of span</span><br><br>
        
    <input type="text" id="in" value="This paragraph is" oninput="highlight()">