Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
49
rated 0 times [  56] [ 7]  / answers: 1 / hits: 20811  / 13 Years ago, sun, january 29, 2012, 12:00:00

What is the best way to highlight a specific substring in a div element in an event?
By highlight, I mean apply some CSS style, like yellow background or something.



Basically I need a simple JS client side function of the form:



function (element, start, end) { 
// element is the element to manipulate. a div or span will do
// start and end are the start and end positions within the text of that
// element where highlighting should be.
// do the stuff
}


Only one highlight will be active.


More From » jquery

 Answers
7

You will need to wrap the text that you want to in it's own <span> tag so you can give that text its own style. Using your requested function definition, you could do it like this:



function (element, start, end) { 
var str = element.innerHTML;
str = str.substr(0, start) +
'<span class=hilite>' +
str.substr(start, end - start + 1) +
'</span>' +
str.substr(end + 1);
element.innerHTML = str;
}


You can then define CSS for the class hilite to control the style of that text.



.hilite {color: yellow;}


This assumes that start and end are indexes into the innerHTML of the first and last characters that you want highlighted.



If you want to be able to call it repeatedly on the same element (to move the higlight around), you could do it like this:



function (element, start, end) {
var item = $(element);
var str = item.data(origHTML);
if (!str) {
str = item.html();
item.data(origHTML, str);
}
str = str.substr(0, start) +
'<span class=hilite>' +
str.substr(start, end - start + 1) +
'</span>' +
str.substr(end + 1);
item.html(str);
}

[#87752] Friday, January 27, 2012, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kaley

Total Points: 141
Total Questions: 109
Total Answers: 109

Location: Burundi
Member since Sat, Aug 21, 2021
3 Years ago
;