John John - 2 months ago 13
Javascript Question

Changing text color using replace method

I am using the following code inside my click handler (shown in JSFiddle below) to replace a text when a user clicks on a cell value:

var value = event.args.value;
var color = "#FF0000";

var highlighted = text.replace(
' ' + value + ' ',
"<span style='color:" + color + ";'</span> "

panel.jqxPanel('append', highlighted);

It is behaving in a different manner. I mean when I click on the first cell value, it converts everything to red color, clicking on other values makes it behave in different manner as can be seen in my JSFiddle here

Q2. What can I use to preserve the html formatting? I mean using
var text = panel.html();
instead of
var text = panel.text();
didn't work for me.


You are missing the closing > on your span tag, and you are omitting the value that you obtained from var value = event.args.value; so the word goes missing.

var highlighted = text.replace(
            ' ' + value + ' ', 
            ' <span style="color:' + color + ';">' + value + '</span> '
//                                              ^    ^^^^^

Note I also changed the quote characters used so the HTML can have the double-quotes " which are more commonly used in markup, and javascript doesn't care about single or double quotes for strings — use whichever you like, just be consistent, for your own sanity.

Try the updated fiddle I created, changing only that line, and you will see the word you click on get highlighted.

That said, it is generally better to avoid inline styles like color="#FF0000" and use classes and CSS styles for them instead. You could instead have simpler code that doesn't have to work the var color into it:

var highlighted = text.replace(
            ' ' + value + ' ', 
            ' <span class="selected">' + value + '</span> '

Your CSS would have a rule span.selected { color: #FF0000; } ... then, restyling your highlight color from red to something else you just change the CSS instead of having to change your javascript code.