I want to attach a class to an object based on cursor position.
I understand the basics of range
, and can get/manipulate selected text, but I'm at a loss as to how I can use the cursor to attach a class to the object it's currently in.
I've through about maybe adding a temporary element at the cursor then traversing to the parent element and attaching the class before removing the temporary element. That really seems messy though, and I would have to assign something to initialize it (keyboard shortcut or on keydown
).
Any ideas? I've search around but haven't found anything like what I'm wanting.
Thanks to John's lead and results from a more appropriate search term, I found this:
Javascript: Detect Carets Parent Node
To answer the question, here's how it's done.
Then, initialize it however you prefer, for example:
Here's a fiddle to demonstrate.