I've written a jQuery function as:
function linkify(parent, regex, url) {
var children = parent.children('main,article,div,p,li,ul,ol,span');
const re = RegExp(`(${regex})(?![^<]*>|[^<>]*<\/)`, 'ig');
children.each(function() {
linkify($(this), regex, url);
$(this).html(
$(this)
.html()
.replace(re, `<a rel="nofollow" href="${url}">$1</a>`)
);
});
}
It's a recursive function that goes down the DOM tree, and finds occurrences of words in the body text, and converts them into a link if found.
It works great. The problem I have is that when I do:
$(this).html(
$(this).html()
)
(i.e. copying the HTML), it discards all bound event handlers. This means in a real page, it can break things like JS menus.
How can I copy the HTML code, while preserving anything bound to it?
PS I have checked other similar posts, however this is different, in that this code will be included in an arbitrary page- I need to develop a general solution, not one specific to particular page.