简体   繁体   中英

Rangy manipulation DOM in loop of ranges

I have a set of ranges, created from the tokensToRanges function in:

Convert tokens into selection ranges

Now I want to loop over each range, and apply an action to them. However I get an error:

Uncaught Error: Range error: Range is no longer valid after DOM mutation ([WrappedRange("foobar":6)])

Now I understand why I am getting the error, but I am wondering how can I loop over a set of ranges, and manipulate each one?

It's a tricky problem that I've run up against several time. Your options are basically:

  1. Convert the list of ranges to a list of range boundaries. For each pair of boundaries, create a range, do your DOM manipulation and adjust any of the remaining range boundaries that need adjusting.
  2. Refactor the code that generated your list of ranges to give you one range at a time.

I ran up against this problem when using the text highlighter. It seems to happen when you are modifying the contents of the scope you are trying to search. In my case, I just used the hidden span elements to encapsulate my text rather than trying to parse the ranges themselves, then class of the hidden span to manipulate its contents, then unwrapped the hidden span.

It may not work in your case, but for me the solution was to simply widen the scope to a div element that enclosed the one on which I was modifying.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM