Fix – Javascript try if document.body.innerhtml var a not working
Posted on: February 11, 2021 by Deven
If Javascript try if document.body.innerhtml is not working for you. The main reason for this error can be getting Aside from overwriting page HTML with a single value each iteration.
When you replace the entire page HTML and break its javascript events such as click/hover handlers and many others attached via addEventListener or .on properties. Also, you overwrite the entire page, thus forcing the browser to parse it entirely and repaint.
Consider the following example for The correct approach. All you need to replace is just the nodes that contain title text:
// title-to-href map used for bulk regexp-replacement
var linkMap = {};
var linkTitles = [];
for (var i = 0, link; (link = document.links[i++]); ) {
if (link.title) {
linkTitles.push(escapeForRegex(link.title));
linkMap[link.title] = link.href;
}
}
// regexp that matches all titles
var titlesRx = new RegExp(linkTitles.join('|'), 'g');
// iterate all text nodes and build a list of elements that contain titles
var nodesToReplace = [];
var walker = document.createTreeWalker(document.body, NodeFilter.SHOW_TEXT);
while (walker.nextNode()) {
var node = walker.currentNode;
var newHTML = node.nodeValue.replace(titlesRx, function(title) {
return '<a href="' + linkMap[title] + '" title="' + title + '">' + title + '</a>';
});
if (newHTML != node.nodeValue) {
nodesToReplace.push({node: node, html: newHTML});
}
}
// replace the contents of affected elements
var scratchpad = document.createElement('div');
nodesToReplace.forEach(function(info) {
scratchpad.innerHTML = info.html;
for (var i = 0, child; (child = scratchpad.children[i++]); ) {
info.node.parentNode.insertBefore(child, info.node);
}
info.node.remove();
});
function escapeForRegex(s) { return s.replace(/[{}()\[\]\/\\.+?^$:=*!|]/g, "\\$&"); }
Share on social media
//