I’m currently facing an issue with JavaScript execution after dynamically replacing the HTML content in my web application using JavaScript.
CURRENT FUNCTION:
function insertHTML(decodedData) {
// Method 1 Parse decoded HTML
const decodedHTML = decodedData;
const parser = new DOMParser();
const doc = parser.parseFromString(decodedHTML, 'text/html');
document.documentElement.replaceWith(doc.documentElement);
// Method 2 Replace current document
document.open();
document.write(decodedHTML);
document.close();
}
EXPECTED CODE In decodedData variable:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
<meta name="viewport" content="width=device-width, initial-scale=1.0"/>
<link rel="stylesheet" href="/assets/css/fontawesome.min.css"/>
<title>Title of Page</title>
<style>
</style>
</head>
<body class="dark-theme">
<script>
var notify = {
timeout: "3000",
}
</script>
<div class="layout">Content Here</div>
<script src="js/jquery.min.js"></script>
<script src="js/jquery-migrate.js"></script>
<script src="js/bootstrap.bundle.min.js"></script>
<script src="js/custom.js"></script>
<script>
// Color Switcher
$(".color-switcher").on('click', function () {
"use strict"
$("body").toggleClass("dark-theme");
var url = '/theme-mode';
$.get(url)
});
</script>
</body>
</html>
ISSUE:
It does not execute the JavaScript however the CSS works.
- I pass decoded HTML string it has full page content from (!DOCTYPE To the ).
- I replace the entire current document’s HTML content and will execute all the new JavaScript files and code which is replaced.
New contributor
Abdul Rehman is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.