Search code examples
jquerycolorstextcolor

colorize a word by entering its rank number


please, how can I colorize a word by entering its rank number using jQuery?

example:

<div id="example">
<p class="txt">hello my best friend</p>
<input type="number" id="myNumber">
<button>Color it</button>
</div>

when I enter (2,3) and press the button, the words "my" and "best" become yellow (#ffbe00)


Solution

  • Use this here jsfiddle

    (function ($) {
       
    var SetColor=function(){   
        var str=$(".txt").text().split(' ');
        $(".txt").empty();
        var filter=$("#myNumber").val().replace('(','').replace(')','').split(',');
        for(var i=0;i<str.length;i++){
    
           for(var j=0;j<filter.length;j++){
            if((i+1)==filter[j]){        
                str[i]="<span style='color: yellow;'>"+str[i]+"<span>";           
                }
           }    
        $(".txt").append(str[i]+" ");
        
        } 
    } 
    
    $("#btn").on("click",SetColor);
    })(jQuery);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <div id="example">
    <p class="txt">hello my best friend</p>
    <input type="text" id="myNumber">
    <button id="btn">Color it</button>
    </div>