techie_28
techie_28

Reputation: 2133

Coloring the character using charAt JavaScript

This may seem to be a silly question and I am sorry if it is.

I am in need to color a character present inside a string and to locate this character I am using JavaScripts string.charAt() from a editable div,this is needed to highlight the matching braces in the string e.g string

abcdef{gh13435}

In above mentioned string if the cursor's location is at the opening brace then I will assign some color to it and its closing piece in order to highlight them.

I can locate the character using charAt function but after that is there a way of assigning the color to the character without wrapping it inside a HTML tag(span,font or any other) like accessing its style property or something else? Might be Im missing some basics here. . I searched it a lot but didn't found anything relevant.

Help/directions are appreciated.

Thanks.

Upvotes: 0

Views: 346

Answers (2)

collapsar
collapsar

Reputation: 17238

As Greg said, the color is not an attribute of the characters you print.

You might implement your design by displaying 2 divs with suitable background color beneath the matching characters you wish to highlight.

however this would require to properly identify the screen position of the respective characters, to add positioning code, probably setting up 2 divs for your editing pane (one on top holding your text with transparent background, one at the bottom with the desired background color of your editing pane) which would sandwich the highlighting divs, definitely setting up some keypress handlers (or additions to their code, respectively), and most liekly some other gadgets that elude my mind right now.

honestly, i wouldn't consider this being worth the trouble (assuming it was a viable approach at all).

keep to Greg's answer, that's the sensible way to go.

Upvotes: 1

Greg Hornby
Greg Hornby

Reputation: 7798

No you'll definitely have to wrap it inside another tag like span or font. That's how html works.

Upvotes: 4

Related Questions