views:

29

answers:

1

I am in search for an efficient method to replace a couple of DOM Elements - if possible in one action only. It is needed for augmenting TextNodes. If a certain word is present, it shall be wrapped in span-Tags, to which an event handler needs to be assigned later.

so if a text Node contains the word it needs to turn from

-#textNode

to

- #textNode
- span
  - #textNode
- #textNode

While leaving the rest of the document untouched.

Known/assumed issues: - innerHTML would be fast, but the Elements would need to have a generated ID and be later retrieved later again via getElementByID; not the cleanest/fastest way. - Cloning the node, putting it into an documentFragment, doing all operations and replacing it back again would be good – but cloning does discard event handlers as far as I know. Since this code is to be used in an Bookmarklet/Add-On this is not an option than.

+2  A: 

Use the DOM Level 1 Core method splitText on the Text node, once on the point just after the target text then once just before. createElement a new span, replaceChild the middle Text node (containing the target text) and appendChild that Text node into the span. Add event handlers etc. to the span as necessary.

No need to start messing with innerHTML or clever Range/adjacentHTML hacks; you're not really going to get any faster than this. Don't believe the hype: DOM manipulations like splitText or a single insertion aren't slow at all. It's only when you try to manipulate a lot of contiguous nodes all at once that other methods can improve matters.

bobince