Reputation: 31
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>
Upvotes: 2
Views: 764
Reputation: 12395
Create a variable to store entered phrase:
var word = '';
Write an event handler
$(document).on('keypress', highlight);
Now implement hightlight
function:
function highlight(event) {
// ...
}
Add pressed key to phrase:
word += String.fromCharCode(event.which);
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);
});
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?
Upvotes: 3
Reputation: 119847
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+'")');
Upvotes: 1