I have a contenteditable element with some nested spans to provide styling inside of it. I need to find out what the css classes are at any given offset of the elemebt. For example, I might have something like this:
<div contenteditable>
<span class"nothing"> </span>
<span class="outer">my <span class="other">name</span> is </span><span class="name">Andrew</span>
</div>
And the text on the screen will look like this (with appropriate styling):
my name is Andrew
Now, imagine that the contenteditable area could be much bigger and have many nested span elements. At any given Given an offset into the text, I need to be able to calculate the css classes that contain it.
For example, let’s say I need that css styles at the offset 4, which is the n of name. I would expect the result to be:
outer other
An equivalent solution is that is if given an offset, (say 4), I can calculate the html element that is wrapping that location (in this case, it would be:
<span class="other">name</span>
I am using jquery, but no other libraries. How can I easily calculate this?
EDIT: I was using a textarea earlier, but that won’t work. I should be using a contenteditable div element.
I suggest inserting a temporary dummy span, grab it with Jquery, then ascend
parentspushing the class list onto an array until you hit your outer container. Of course if you only want thecurrentStyle, that’s even easier.As to how to get your dummy span into the textarea, if you only have a character position, see Insert text into textarea at cursor position (Javascript). If you want to insert at the caret, see Insert text into textarea with jQuery.