Skip to content

Replace the text with new text #4

@badsyntax

Description

@badsyntax

Hi James. Firstly, thanks a lot for this code!

All the examples I've seen have demonstrated how to wrap text with an element node.

I wanted to know if you had any ideas for adapting this code to provide an API method to actually replace the text in the DOM?

For example: I have the following DOM tree:

<div>
    badw<strong>o<em>rd</em></strong>d
</div>

I want to replace the word 'badwordd' with 'bad word' in the above DOM tree.

I've had a go at doing this myself by providing a handler function for the replacementNode argument, but the issue here is that the replacementNode function is called in the incorrect order.
It seems the recursive logic for traversing the tree does not match the order of the word you are searching for.

For example:

findAndReplaceDOMText(new RegExp(oldWord), this.element[0], function(fill){
    console.log(fill);
    return document.createTextNode(fill);
});

/* will output:
badw
d
o
rd 
*/

The order in which the replacementNode handler is called makes it a bit tricky for me to replace the 'fill' value with something else.

If you have any ideas on how to do this elegantly, it would be most appreciated.

Thanks,
Rich

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions