2

I want change the background color of limited character in a string

I have text box and string, I want to change the background-color of the string from the text box
Using Jquery eg:

When I enter the text 'char' in the text box i need to change all 'char' and 'CHAR' text listed ul

<ul class="brows_all_cat"> <li><a> My sample character1 </a></li> <li><a> My sample CHARACTER2 </a></li> <li><a> My sample character3 </a></li> <li><a> My sample character4 </a></li> </ul> 

2 Answers 2

3
  1. Create a variable to store entered phrase:

    var word = '';

  2. Write an event handler

    $(document).on('keypress', highlight);

  3. Now implement hightlight function:

    function highlight(event) { // ... } 
    1. Add pressed key to phrase:

      word += String.fromCharCode(event.which); 
    2. Extract innerText from all <a> elements, then add hightlights, by wrapping phrase with an <span> element

      $('li>a').each(function() { var element = $(this); var text = element.text(); text = text.replace(new RegExp('(' + word + ')', 'ig'), '<span class="highlight">$1</span>'); element.html(text); }); 
  4. Add a style to .highlight selector:

    <style> span.highlight { color: red; } </style> 

By combining all code, it should be like below:

var word = ''; function highlight(event) { word += String.fromCharCode(event.which); $('li>a').each(function() { var element = $(this); var text = element.text(); text = text.replace(new RegExp('(' + word + ')', 'ig'), '<span class="highlight">$1</span>'); element.html(text); }); } $(document).on('keypress', 'highlight'); 

There is still one problem left, when would be the phrase be cleared, after a certain time that document doesn't receive any keypress event, or is there any other strategy?

Sign up to request clarification or add additional context in comments.

1 Comment

deleted my answer, cause this one is far more accurate, informative and just plain awesome ;)
1

i think you mean the .contains() selector, especially making it case-INsensitive

//make :contains() case insensitive jQuery.expr[':'].Contains = function(a, i, m) { return jQuery(a).text().toUpperCase().indexOf(m[3].toUpperCase()) >= 0; }; //then var elementsThatHaveText = $('.brows_all_cat a:contains("'+text_you_need+'")'); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.