How to get the element(s) created when text is highlighted with document.execCommand

246 views Asked by At

How can I retrieve the element that is created to wrap text with a highlighted background when using document.execCommand('BackColor', false, color) (or 'HiliteColor')? For reference, I'm using Tim Down's solution to highlight selected text: https://stackoverflow.com/a/2583895/494954.

I know I could get a node in the selection, and go up the chain until I found an element that has the background color that I specified, but I'm wondering if there's a more elegant solution?

1

There are 1 answers

1
Tim Down On BEST ANSWER

There isn't really an elegant solution. You can use DOM mutation events for now in IE >= 9 and non-IE browsers but there's a good chance these events will be removed in future in favour of Mutation Observers. Here's a demo that uses the DOMNodeInserted event. It only detects the elements that have been inserted and doesn't filter out any that aren't highlighting elements:

http://jsbin.com/joqofojetu/1/

It would be possible to implement a similar solution with mutation observers, with two disadvantages: first, IE only supports them from version 11 onwards. Second, unlike mutation events, mutation observers are not guaranteed to fire synchronously so you'd have to wait a while before processing the elements you've collected.