1

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?

Community
  • 1
  • 1
lakenen
  • 3,436
  • 5
  • 27
  • 39

1 Answers1

1

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.

Tim Down
  • 318,141
  • 75
  • 454
  • 536
  • Yeah, it seems like a bit of a hack, but at least it's a little cleaner than my original solution. Thanks! – lakenen Nov 24 '14 at 18:18